Performance in .NET – Part 4

Introduction

This is my fourth post on performance in the .NET world. See the first one on object instantiation here and the second on property copying here and the third here. This time I’m going to talk about collections, but focusing on the performance side.This time, I’ll be talking about value types.

Value Types versus Reference Types

Value types – structs and enums – are always allocated in the stack, as opposed to reference types – classes - , which are allocated in the heap. This means that value types are automatically released from memory when they go out of scope – end of the block/method where they are declared, or the class is garbage collected, which is more rare. Value types are thus cheaper to create and do not need to be checked by the garbage collector.

Some aspects, though, need attention.

Instance Comparison

When you compare two value types using the Equals method, if there is no override for it, the value type is compared byte by byte. This is, as you can image, pretty inefficient. Is is recommended that you implement your own Equals (and GetHashCode too) and also that you implement IEquatable<T> interface for comparing two instances of your value type without incurring into boxing and unboxing.

Usage in Lists

Storing value types in array-based lists that permit reordering (random insertions and deletions), such as List<T> is painful, because of the items need to be copied, and copying for value types means byte by byte copying. Avoid if possible.

Usage in Arrays

Value types are great for usage in arrays, because a value type has no object header, so it’s size in memory is very small. The size of the array is therefore small when compared to the same array of reference types.

Conclusion

Do use value types as much as possible, but stay aware of the problems. As always, looking forward to hearing your thoughts. I’ll be back for more.


                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website