Home
Blog
Best C# Optimization
Updated
Dot Net Perls

Best C# Optimization

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:

Arrays are allocated on the managed heap, so if we reduce the creation of arrays, this will help.
Types like StringBuilder are also placed on the heap, so we should reuse a single StringBuilder instead of creating many of them.
Any 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.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen