List<Int32> numberList = new List<Int32>();for(Int32 i = 0; i < 13; i++){ numberList.Add(i);}ArrayList listCopy = new ArrayList();for(Int32 i = 0; i < 100000; i++){ // make a copy of the collection foreach(Int32 num in numberList) { listCopy.Add(num); } // we no longer need the list contents listCopy.Clear();}
This example generated boxed 1,300,000 times and the Garbage Collector ran 14 times in under 20 seconds! That is an incredible rate of collection. From the GC latency time, we can see that the Garbage Collector was running very efficiently since there were not many live objects at the time of the collections.Please notice that even though we collected a large amount of data (15,508,684 bytes) during the runtime of the application, the device was not put under heavy memory pressure -- the GC Heap stayed below 1 MB for the duration of the application.Removing the boxingIf we modify the example to replace the ArrayList with a second List<Int32> and re-run the test, we see the following data.
As we can see from this set of data, the second version took less than half of the time to run as did the first -- all boxing has been eliminated and no garbage collections occurred. We also used considerably less memory (only 64k) since no objects needed to be constructed.If you use the .NET Compact Framework Remote Performance Monitor, the data above becomes very easy to see in real time.During the MEDC booth demo, I ran these examples in tight loops within a worker thread. After 20-30 minutes, the counter for Bytes Collected By GC pegged (got to Int32.MaxValue). We were still collecting, but the counters could no longer track how much data we collected yet the GC Heap size never exceeded 1114112 bytes. The application was doing a huge number of collections, yet was still memory "friendly" on the device.Please be sure to remember that this is an extreme micro-benchmark example. Value type boxing can be useful in moderation, and does not necessarily cause dramatic application performance issues by itself. It is important to measure application / algorithm performance early and often.Take care,-- DKDisclaimer(s):This posting is provided "AS IS" with no warranties, and confers no rights. Some of the information contained within this post may be in relation to beta software. Any and all details are subject to change.