Why you should care about Boxing and Unboxing

Most people probably will not run into a situation where boxing and unboxing are going to really matter in their applications, others do. Read this post to see how a module’s heap usage went from 103MB to 16MB.

Take the TagLib.ByteVector class. It serializes many formats of data into a collection of bytes. However, it was using the System.Collections.ArrayList class to store these bytes! As a byte type is stack-based data, and ArrayList stores heap-based data, each stack-based member of the collection must be boxed for storage and unboxed for retrieval.

Simply by replacing ArrayList with List, the excessive memory problem goes away, since the type to be stored in the collection is known at compile time, and thus boxing/unboxing is no longer necessary.


Leave a Reply