Performance improvement tips for C# code
2 min readJan 6, 2023
I am just summarizing below points for performance improvements in C# code.
These are some pointers applicable to most cases though their application will be case specific.
- Use struct over class for small value types as they are stored on stack for faster access
- Use foreach over for as it avoids index variable overhead
- Use string.Concat in some cases instead of + operator as new strings not created for each concatenation
- Use Copy() method of array over manual copy
- StringBuilder for large string loops concatenation
- Use async await for making application responsive
- Avoid boxing and unboxing that happens unintentionally
- Use Dictionary and Hastable over List and Array for searching
- Reuse objects instead of creating new ones unnecessarily where required
- Use value types over reference types where appropriate as they are stored on stack with faster access
- Consider loop over LINQ as LINQ queries are slower
- Use caching to store result of expensive operations
References:
- Choosing Between Class and Struct — Framework Design Guidelines | Microsoft Learn
- Comparing the Performance of `for` vs. `foreach` Loops (csharpplayersguide.com)
- c# — Most efficient way to concatenate strings? — Stack Overflow
- c# — Most efficient way to concatenate strings? — Stack Overflow
- C# Await Async | How does Await and Async Work in C#? (educba.com)
A few more tips below:
Top 11 C# Tips to Improve Code Quality and Performance — (code-maze.com)