Compare the efficiency of a generic collection and a non-generic collection in operation:
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacelistdemo{classProgram {Static voidMain (string[] args) {Console.WriteLine ("start test ArrayList:"); Testbegin (); Testarraylist (); Testend (); Console.WriteLine ("start Test list<t>:"); Testbegin (); Testgenericlist (); Testend (); Console.read (); } Static intCollectioncount =0; StaticStopwatch Watch =NULL; Private Static intTestcount =10000000; Static voidTestbegin () {GC. Collect ();//force an instant garbage collection of all codeGc. WaitForPendingFinalizers ();//suspending a thread, executing finalizers in the finalizer queue (destructor method)Gc. Collect ();//garbage collection of all code again, mainly including objects from the finalizer queueCollectioncount = GC. Collectioncount (0);//returns the number of garbage collections performed in generation 0Watch =NewStopwatch (); Watch. Start (); } Static voidTestend () {watch. Stop (); Console.WriteLine ("time consuming:"+Watch. Elapsedmilliseconds); Console.WriteLine ("garbage collection Times:"+ (GC. Collectioncount (0)-collectioncount)); } Static voidtestarraylist () {ArrayList Al=NewArrayList (); inttemp =0; for(inti =0; i < Testcount; i++) {al. ADD (i); Temp= (int) Al[i]; } Al=NULL; } Static voidtestgenericlist () {List<int> LISTT =Newlist<int>(); inttemp =0; for(inti =0; i < Testcount; i++) {listt.add (i); Temp=Listt[i]; } LISTT=NULL; } }}
If the number of collections is fixed and does not involve transformation, use an array with high efficiency or use LIST<T>.
C # Generic Collection