Performance improvement tips for C# code

Siddharth Phatarphod
2 min readJan 6, 2023

--

CSharp

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.

  1. Use struct over class for small value types as they are stored on stack for faster access
  2. Use foreach over for as it avoids index variable overhead
  3. Use string.Concat in some cases instead of + operator as new strings not created for each concatenation
  4. Use Copy() method of array over manual copy
  5. StringBuilder for large string loops concatenation
  6. Use async await for making application responsive
  7. Avoid boxing and unboxing that happens unintentionally
  8. Use Dictionary and Hastable over List and Array for searching
  9. Reuse objects instead of creating new ones unnecessarily where required
  10. Use value types over reference types where appropriate as they are stored on stack with faster access
  11. Consider loop over LINQ as LINQ queries are slower
  12. Use caching to store result of expensive operations

References:

  1. Choosing Between Class and Struct — Framework Design Guidelines | Microsoft Learn
  2. Comparing the Performance of `for` vs. `foreach` Loops (csharpplayersguide.com)
  3. c# — Most efficient way to concatenate strings? — Stack Overflow
  4. c# — Most efficient way to concatenate strings? — Stack Overflow
  5. 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)

--

--

Siddharth Phatarphod

Full Stack | Angular| .Net| .Net Core| SQL | Azure PaaS | Azure DevOps | Git | Scrum