Problem:
You want to replace all arraylists with generics to improve application performance and simplify the code. This is necessary when you find that struct or other types of values are stored in these data structures, resulting in packing/unpacking operations.
Solution:
Show allSystem. Collections. arraylistClass with better performance genericSystem. Collections. Generic. ListClass substitution.
Here is a simple example of using the system. Collections. arraylist class:
Public static void usenongenericarraylist ()
{
// Create and populate an arraylist.
Arraylist numbers = new arraylist ();
Numbers. Add (1); // causes a boxing operation to occur
Numbers. Add (2); // causes a boxing operation to occur
// Display All integers in the arraylist.
// Causes an unboxing operation to occur on each iteration
Foreach (int I in numbers)
{
Console. writeline (I );
}
Numbers. Clear ();
}
Here is a usageSystem. Collections. Generic. ListSimple Example:
Public static void usegenericlist ()
{
// Create and populate a list.
List <int> numbers = new list <int> ();
Numbers. Add (1 );
Numbers. Add (2 );
// Display All integers in the arraylist.
Foreach (int I in numbers)
{
Console. writeline (I );
}
Numbers. Clear ();
}
Discussion:
Because arraylist is used in almost all applications, this is the first good place to improve performance. In some simple applications, using this alternative method to implement arraylist is very simple. However, there are several points worth noting. For example, the generic list class does not implement the icloneable interface, but the arraylist class does.
NOTE: If no generic list of the synchronization version is returned and no generic list of the specified size is returned, the isfixedsize and issynchronized attributes always return false. The syncroot attribute always returns an object that is the same as it. In fact, this property returns the this pointer. Microsoft recommends that you use the lock keyword to lock the entire set or other synchronization objects you use.
PS: arraylist has 16 elements by default, while list <t> has 4 elements. That is to say, if 17th elements are added to the List <t>, the list <t> will be re-allocated three times, while the arraylist will only need one time. This should be considered for program performance.