Showing posts with label best coding practices in C#. Show all posts
Showing posts with label best coding practices in C#. Show all posts

Tuesday, October 14, 2025

🚀 How to Improve Performance in C# — Code Refactoring and Optimization Guide

 🧠 Introduction

Performance plays a crucial role in any C# or .NET application. As your application grows, inefficient code and unnecessary computations can slow it down drastically.
To keep your app fast, scalable, and maintainable, you must regularly perform code refactoring and optimization.

In this article, you’ll learn:

  • What performance optimization means in C#

  • Refactoring techniques to simplify and speed up your code

  • Real-time C# examples to apply in your project

  • Best practices for memory management and efficiency


⚙️ What is Code Optimization?

Code Optimization is the process of making your C# code run faster and use fewer resources — without changing its output or functionality.

Example:

// Before Optimization string result = ""; for (int i = 0; i < 10000; i++) { result += i.ToString(); // Creates new string each time — inefficient } // After Optimization using StringBuilder StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10000; i++) { sb.Append(i); } string result = sb.ToString(); // Much faster and memory efficient

👉 Why?
String is immutable in C#, meaning every concatenation creates a new object in memory. StringBuilder avoids this, improving speed and reducing garbage collection pressure.


🧩 What is Code Refactoring?

Refactoring means restructuring existing code to make it cleaner, readable, and maintainable — without changing its external behavior.

Example:

// Before Refactoring if (user.Age >= 18) { if (user.HasDrivingLicense) { Console.WriteLine("Eligible to drive"); } } // After Refactoring (Better readability) if (IsEligibleToDrive(user)) { Console.WriteLine("Eligible to drive"); } bool IsEligibleToDrive(User user) => user.Age >= 18 && user.HasDrivingLicense;

Benefits of Refactoring:

  • Improves readability and maintainability

  • Reduces duplicate code

  • Makes debugging and testing easier

  • Helps spot performance bottlenecks


⚡ Top Techniques to Improve Performance in C#

1. Use Appropriate Data Structures

Choose the right collection for your need:

// ❌ Wrong: List lookup O(n) if (myList.Contains(id)) { ... } // ✅ Right: HashSet lookup O(1) if (myHashSet.Contains(id)) { ... }

Tip:
Use Dictionary<TKey, TValue> for key-value pairs, and HashSet<T> for quick lookups.


2. Avoid Unnecessary LINQ Queries

LINQ is powerful but can be slow for large datasets.

// ❌ Multiple enumerations var activeUsers = users.Where(u => u.IsActive); int count = activeUsers.Count(); var first = activeUsers.FirstOrDefault(); // ✅ Single enumeration var activeUsersList = users.Where(u => u.IsActive).ToList(); int count = activeUsersList.Count; var first = activeUsersList.FirstOrDefault();

3. Use Asynchronous Programming

Leverage async/await for I/O operations like file access, web API calls, or database queries.

// ❌ Blocking call var data = GetData(); Console.WriteLine(data); // ✅ Non-blocking var data = await GetDataAsync(); Console.WriteLine(data);

Async improves responsiveness, especially in web and desktop applications.


4. Minimize Object Creation

Avoid creating objects repeatedly inside loops.

// ❌ Creates object each time for (int i = 0; i < 1000; i++) { var obj = new HeavyObject(); obj.DoWork(); } // ✅ Create once and reuse var obj = new HeavyObject(); for (int i = 0; i < 1000; i++) { obj.DoWork(); }

5. Use Caching Strategically

For expensive operations (like database or API calls), use caching.

private static readonly Dictionary<int, string> _cache = new(); public string GetUserName(int userId) { if (_cache.ContainsKey(userId)) return _cache[userId]; string name = GetUserFromDatabase(userId); _cache[userId] = name; return name; }

6. Avoid Boxing and Unboxing

When value types are treated as objects, C# performs boxing/unboxing, which is expensive.

// ❌ Causes boxing ArrayList list = new ArrayList(); list.Add(10); // int -> object (boxed) // ✅ Use Generics List<int> list = new List<int>(); list.Add(10);

7. Dispose Unused Resources

Always use using statements for disposable objects like files, streams, or database connections.

using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); // perform DB operations } // Automatically disposes

8. Optimize Database Calls

  • Use stored procedures instead of raw queries.

  • Use Dapper or EF Core compiled queries for better performance.

  • Avoid fetching unnecessary columns or rows.

Example:

// ❌ Bad var users = db.Users.ToList(); // loads all users // ✅ Good var users = db.Users.Where(u => u.IsActive).Select(u => new { u.Id, u.Name }).ToList();

🧮 Memory Optimization Tips

  • Use structs instead of classes for small, immutable types.

  • Avoid large arrays or lists in memory — consider streaming or pagination.

  • Use Span<T> or Memory<T> for performance-sensitive operations.

  • Use pooling for frequently reused objects.


🧰 Tools for Performance and Refactoring

  1. Visual Studio Diagnostic Tools – Analyze CPU and memory usage

  2. dotTrace / dotMemory (JetBrains) – Find bottlenecks

  3. ReSharper – Suggests code refactoring opportunities

  4. BenchmarkDotNet – Compare method performance

  5. SonarQube – Code quality and maintainability analysis


✅ Summary

CategoryTipBenefit
StringsUse StringBuilderReduces memory allocations
CollectionsChoose right data structureFaster lookups
AsyncUse async/awaitImproves responsiveness
MemoryDispose resourcesAvoid leaks
LINQMinimize queriesFaster execution
CachingCache frequent dataSaves database hits
RefactoringClean, modular codeEasier maintenance

✨ Final Thoughts

Performance optimization in C# isn’t about premature tweaking — it’s about writing clean, efficient, and maintainable code.
By combining refactoring principles with smart optimization techniques, you can build .NET applications that are both fast and future-proof.

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages