Should we use the Generic Collection to increase safety and performance?

Should I use the Generic Collection to increase security and performance?

+1
source share
3 answers

Of course. Why not? More important than performance, IMO is the fact that common APIs are more expressive. This applies to general APIs in general, and not just for collections.

EDIT: just clarify a little:

  • Performance characteristics differ slightly between generic and neongeneric collections for reasons “they are different implementations”, as well as the entire generic / unrelated side. Obviously, the generic version avoids boxing / unboxing and (in most cases of use) runtime on extraction. In practice, this is likely to be significant for value types where boxing comes into play. For large collections, this is a difference in memory usage, which is likely to be more significant than a difference in execution speed.

  • I'm a little less worried about the real security aspect. This, of course, is good, but I can’t recall that I have ever seen an error when using inorganic collections due to input of the wrong type (or choosing it as the wrong type). Of course, this is an advantage.

  • I see expressiveness as very important. I can take a look at the method declaration and find out what to expect from the return value - I don’t have to read the documentation carefully or give variables like bulky names or documents. In addition, you get all the benefits of Intellisense, etc. One of the questions asked by the question of the language is "what can I express in it?" and generics allow much richer concepts to express themselves than before.

+5
source

That's right.

A regular collection, such as an ArrayList, implicitly stores objects.

This means that it is:

ArrayList list = new ArrayList(); list.Add(5); list.Add("FooBar"); 

It is a legal code. This causes several problems.

  • Usually you do not want to store different types in the same collection, and checking compile time is good for this.
  • When you store a value type (for example, the integer 5 above), it must be placed in the reference type before it can be stored in the collection.
  • When reading a value, you must drop it back from Object to the desired type.

However, you fix all these problems using a common collection:

 List<int> list = new List(); list.Add(5); // Compile Time Error. list.Add("FooBar") 

You also get intellisense support when working directly with collection indexes, and not just with the common intellisense "object".

+2
source

Short answer: yes

Longer answer: in fact, there are no shortcomings in using shared collections. Checking the type of compilation time eliminates the possibility of runtime errors during casting. Performance will be greater for built-in types such as integers, since boxing and unpacking are not needed (unlike general Java collections, by the way)

+1
source

All Articles