C# is a relatively well-performing language—it is compiled and uses a type system that enables many optimizations. But sometimes good performance is not enough—the C# program needs to be as fast as possible. Probably the best C# optimization is to reduce or eliminate allocations.
In C#, every string
is allocated upon the managed heap, a section of memory that allows variable-length data to be stored. By removing allocations of strings, we can save accesses to the managed heap, and also the later garbage collection passes that clean up the heap.
There are some other types that benefit from reducing allocations:
StringBuilder
are also placed on the heap, so we should reuse a single StringBuilder
instead of creating many of them.class
instances, like strings, are also heap-allocated and can cause garbage collection pauses.Keeping a cache of some sort and reusing these objects instead of allocating new ones has been, in my experience, the most effective C# optimization. You can see some examples on the array and Dictionary
C# articles.