Tuesday, January 5, 2010

C#: Performance: Boxing and Unboxing

You know to avoid boxing and unboxing wherever you can. Don't know what boxing is, read about it here[MSDN], but read on because you'll probably figure it out. Sometimes you can't avoid it, but other times, it can really be avoided so easily. Where?


Yep. ArrayList. If you are storing one type of object in ArrayList, why are you using it? You are wasting CPU cycles with boxing and unboxing. Include a reference to System.Collections and replace that snippet with a typed List.
ArrayList al = new ArrayList();
List<DateTime> typedList = new List<DateTime>();
Now your gains won't be huge like replacing String with StringBuilder, but not only will you gain performance, but you now don't have to worry about type checking, either.

1 comment: