Best Practices for Code Optimization in C# (Simple and Effective Tips)
Karam Khoury
Lead Software Engineer | Certified Team Leader & Scrum Master (PSM I) | Architecting Scalable .NET & Azure Solutions | Driving FinTech Innovations & Cloud Transformations
Hey everyone!
As a .NET developer, writing clean and efficient code is crucial. Today, I want to share some?simple and practical tips?for optimizing your C# code in the latest .NET versions (like .NET 6, 7, and 8). No buzzwords, just clear examples you can use right away. Let’s dive in!
1.?Use?Span<T>?and?Memory<T>?for Performance-Critical Code
When working with large datasets or performance-sensitive operations, avoid unnecessary allocations. Use?Span<T>?and?Memory<T>?to work with slices of arrays or memory without creating new objects.
// Instead of this:
string substring = largeString.Substring(0, 10); // Creates a new string
// Do this:
ReadOnlySpan<char> substringSpan = largeString.AsSpan().Slice(0, 10); // No allocation
2.?Leverage?StringBuilder?for String Manipulation
Concatenating strings in a loop can be expensive because strings are immutable. Use?StringBuilder?instead.
// Instead of this:
string result = "";
for (int i = 0; i < 100; i++)
{
result += i.ToString(); // Creates a new string each time
}
// Do this:
var sb = new StringBuilder();
for (int i = 0; i < 100; i++)
{
sb.Append(i); // More efficient
}
string result = sb.ToString();
3.?Use?record?for Immutable Data Types
If you’re working with data transfer objects (DTOs) or immutable types, use?record?instead of?class. It’s concise and provides value-based equality.
// Instead of this:
public class Person
{
public string Name { get; init; }
public int Age { get; init; }
}
// Do this:
public record Person(string Name, int Age); // Less boilerplate, immutable by default
4.?Avoid Boxing and Unboxing
Boxing (converting value types to objects) is expensive. Use generics to avoid it.
// Instead of this:
ArrayList list = new ArrayList();
list.Add(42); // Boxing happens here
// Do this:
List<int> list = new List<int>();
list.Add(42); // No boxing
5.?Use?async?and?await?properly
Avoid blocking threads with?#.Result#?or?#.Wait().# Use?async?and?await?correctly to keep your application responsive.
// Instead of this:
var result = httpClient.GetAsync(url).Result; // Blocks the thread
// Do this:
var result = await httpClient.GetAsync(url); // Non-blocking
6.?Minimize LINQ Overhead
LINQ is great for readability, but it can be slow for large datasets. Use simple loops or?foreach?when performance matters.
// Instead of this:
var filteredList = bigList.Where(x => x > 10).ToList(); // LINQ overhead
// Do this:
var filteredList = new List<int>();
foreach (var item in bigList)
{
if (item > 10)
filteredList.Add(item); // Faster
}
7.?Use?ArrayPool<T>?for Temporary Arrays
If you need temporary arrays (e.g., for buffers), use?ArrayPool<T>?to reduce garbage collection pressure.
var pool = ArrayPool<int>.Shared;
int[] buffer = pool.Rent(1024); // Rent a buffer from the pool
try
{
// Use the buffer
}
finally
{
pool.Return(buffer); // Return it when done
}
8.?Profile Your Code
Optimization without measurement is guesswork. Use tools like?dotTrace,?Visual Studio Profiler, or?BenchmarkDotNet?to identify bottlenecks.
// Example using BenchmarkDotNet:
[MemoryDiagnoser]
public class MyBenchmark
{
[Benchmark]
public void MyMethod()
{
// Code to benchmark
}
}
9.?Use?IAsyncEnumerable<T>?for Streaming Data
When working with large datasets or streams, use?IAsyncEnumerable<T>?to process data asynchronously without loading everything into memory.
public async IAsyncEnumerable<int> FetchDataAsync()
{
for (int i = 0; i < 100; i++)
{
await Task.Delay(100); // Simulate async operation
yield return i;
}
}
// Consume it:
await foreach (var item in FetchDataAsync())
{
Console.WriteLine(item);
}
10.?Keep It Simple
The best optimization is often writing simple, readable code. Avoid over-engineering or premature optimization. Focus on clean, maintainable code first, and optimize only when necessary.
Final Thoughts
Optimization is about making your code efficient without sacrificing readability. Use these tips as guidelines, but always measure and test your changes. Happy coding!
Lead Software Engineer, Architect
1 周Nice one. Thanks for sharing?
Blockchain Developer | Trading Bot Specialist | Web3 Architect | Automation Expert | NFT | Smart Contract | Crypto | Etherium | Solana Bot Developer
1 周Great tips for .NET and C#! ?? Clean and efficient code is key to building robust applications. Thanks for sharing! ??
Senior Software Developer at Solution
1 周Great advice