Skip to content

Instantly share code, notes, and snippets.

@foontzoot
Last active August 27, 2023 22:33
Show Gist options
  • Save foontzoot/25dca9c57c436bfe4195d66dd3f19b43 to your computer and use it in GitHub Desktop.
Save foontzoot/25dca9c57c436bfe4195d66dd3f19b43 to your computer and use it in GitHub Desktop.
best practices to improve .NET

.NET Best Practices

Use profiling tools

Example: Using Stopwatch to measure method performance

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // Code to profile

        stopwatch.Stop();
        Console.WriteLine($"Elapsed Time: {stopwatch.ElapsedMilliseconds} ms");
    }
}

Caching

Example: Using in-memory caching with MemoryCache

using System;
using Microsoft.Extensions.Caching.Memory;

class Program
{
    static void Main(string[] args)
    {
        IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());

        // Store data in cache
        cache.Set("myKey", "myValue", TimeSpan.FromMinutes(10));

        // Retrieve data from cache
        if (cache.TryGetValue("myKey", out string value))
        {
            Console.WriteLine($"Cached Value: {value}");
        }
    }
}

Database Optimization

Example: Using proper indexing in Entity Framework Core

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        var options = new DbContextOptionsBuilder<MyDbContext>()
            .UseSqlServer(connectionString)
            .Options;

        using (var context = new MyDbContext(options))
        {
            // Apply indexing to optimize queries
            var results = context.Orders.Where(o => o.CustomerId == 123).ToList();
        }
    }
}

Asynchronous Programming

Example: Using async/await to perform I/O-bound tasks asynchronously

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync("https://example.com");
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}

Entity Framework Core Optimizations

Example: Using compiled queries in Entity Framework Core

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        var options = new DbContextOptionsBuilder<MyDbContext>()
            .UseSqlServer(connectionString)
            .Options;

        using (var context = new MyDbContext(options))
        {
            var compiledQuery = EF.CompileQuery((MyDbContext db, int customerId) =>
                db.Orders.Where(o => o.CustomerId == customerId).ToList());

            var results = compiledQuery(context, 123);
        }
    }
}

Memory Management

Example: Disposing resources using the Dispose pattern

using System;

class MyResource : IDisposable
{
    private bool disposed = false;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Release managed resources
            }

            // Release unmanaged resources

            disposed = true;
        }
    }

    ~MyResource()
    {
        Dispose(false);
    }
}

HTTP Caching

Example: Adding caching headers to HTTP responses

using Microsoft.AspNetCore.Mvc;

public class MyController : Controller
{
    [HttpGet]
    [ResponseCache(Duration = 300)] // Cache for 5 minutes
    public IActionResult Index()
    {
        // Generate and return response
    }
}

Minimize Round-Trips

Example: Combining multiple database queries into a single query

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        var options = new DbContextOptionsBuilder<MyDbContext>()
            .UseSqlServer(connectionString)
            .Options;

        using (var context = new MyDbContext(options))
        {
            var orders = context.Orders
                .Include(o => o.Customer)
                .Include(o => o.Products)
                .Where(o => o.CustomerId == 123)
                .ToList();
        }
    }
}

Content Delivery Networks (CDNs)

Example: Using a CDN for delivering static assets

<!-- Link to static asset on CDN -->
<link rel="stylesheet" href="https://cdn.example.com/styles.css">

Compression

Example: Enabling GZIP compression for HTTP responses

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.ResponseCompression;

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCompression(options =>
    {
        options.EnableForHttps = true;
        options.Providers.Add<GzipCompressionProvider>();
    });
}

Logging and Tracing

Example: Using a distributed tracing library for monitoring

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;

var configuration = TelemetryConfiguration.Active;
var telemetryClient = new TelemetryClient(configuration);

using (var operation = telemetryClient.StartOperation<RequestTelemetry>("MyOperation"))
{
    // Perform operation

    operation.Telemetry.Success = true;
}

Parallelism and Concurrency

Example: Using parallelism for CPU-bound tasks

Parallel.For(0, 10, i =>
{
    // Perform parallelized work
});

Benchmarking

Example: Benchmarking an algorithm

public class AlgorithmBenchmark
{
    public void RunBenchmark()
    {
        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();

        // Run the algorithm multiple times and measure the time taken
        for (int i = 0; i < 10000; i++)
        {
            // Call the algorithm being benchmarked
            SomeAlgorithm.Perform();
        }

        stopwatch.Stop();

        Console.WriteLine($"Time taken: {stopwatch.ElapsedMilliseconds} ms");
    }
}

Code Profiling and Performance Monitoring

Example: Integrating Application Insights for monitoring

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;

var configuration = TelemetryConfiguration.Active;
var telemetryClient = new TelemetryClient(configuration);

// Track custom telemetry events
telemetryClient.TrackEvent("CustomEventName");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment