Skip to main content

Command Palette

Search for a command to run...

Performance in C#: Writing Efficient Code Without Sacrificing Readability

Published
2 min readView as Markdown
Performance in C#: Writing Efficient Code Without Sacrificing Readability
D

I'm a fullstack developer and my stack is includes .net, angular, reactjs, mondodb and mssql

I currently work in a little tourism company, I'm not only a developer but I manage a team and customers.

I love learning new things and I like the continuous comparison with other people on ideas.

Often, writing performant code is seen as a trade-off between speed and cleanliness.
In reality, it is possible to write efficient code without giving up readability and maintainability by applying some best practices and careful considerations.


Measure Before You Optimize

Use profilers (e.g., Visual Studio Profiler, dotTrace) to identify real bottlenecks.
Optimize only critical code.


Avoid Unnecessary Allocations

Use value types (structs) when appropriate.
Prefer Span<T> or Memory<T> to manipulate buffers without copies.
Be careful with strings: use StringBuilder for repeated concatenations.


Use Appropriate Collections

Choose collections that best fit your scenario (List<T>, Dictionary<TKey,TValue>, HashSet<T>).
Avoid thread-safe collections if not needed (they have overhead).


Avoid Boxing and Unboxing

When using value types in object or interface contexts, boxing can cause overhead.
Use generics to avoid boxing.


Lazy Loading and Caching

Load heavy resources only when necessary.
Cache expensive results for reuse.


Parallelism and Asynchrony

Use Parallel.ForEach, Task.Run, and async/await to leverage multithreading.
Be careful not to create too many threads, as it can worsen performance.


Practical Example

Before:

string result = "";
for (int i = 0; i < 1000; i++)
{
    result += i.ToString() + ",";
}

After:

var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
    sb.Append(i);
    sb.Append(",");
}
string result = sb.ToString();

Beware of Premature Optimization

Don’t optimize too early; you risk making the code unnecessarily complicated.
Clean code and readability remain priorities.


Conclusion

Knowing the basics of performance in C# allows you to write efficient code while maintaining good cleanliness and maintainability.
Measure, profile, and optimize wisely.

More from this blog

F

Fabio Developer Life

76 posts

.NET enthusiasm with great passion of architecture, pattern and software metholodgy