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");
}
}
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}");
}
}
}
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();
}
}
}
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);
}
}
}
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);
}
}
}
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);
}
}
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
}
}
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();
}
}
}
Example: Using a CDN for delivering static assets
<!-- Link to static asset on CDN -->
<link rel="stylesheet" href="https://cdn.example.com/styles.css">
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>();
});
}
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;
}
Example: Using parallelism for CPU-bound tasks
Parallel.For(0, 10, i =>
{
// Perform parallelized work
});
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");
}
}
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");