Performance is paramount when developing web applications. A slow, unresponsive application results in poor user experience, losing users, and possibly business. For ASP.NET Core developers, there are many techniques and best practices to optimize application performance. Lets explore some of these approaches in this article.
When we talk about performance, the first thing to ask is Where is the issue? Without understanding where the bottlenecks are, we could end up optimizing parts of our application that wont have a significant impact on overall performance.
There are many tools and techniques to identify performance bottlenecks in an ASP.NET Core application:
One of the simplest approaches is to add logging and metrics to your application. You can measure how long operations take and log any issues that occur.
ASP.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. You can configure the built-in logging providers to output logs to the console, debug, and event tracing.
Heres an example of how you can use the ILogger service to log the execution time of a method:
public IActionResult Index(){var watch = Stopwatch.StartNew();
// Code to measure goes here...
watch.Stop();var elapsedMs = watch.ElapsedMilliseconds;_logger.LogInformation("Index method took {ElapsedMilliseconds}ms", elapsedMs);
return View();}}
A more advanced way to identify performance bottlenecks is to use a profiler. A profiler is a tool that monitors the execution of an application, recording things like memory allocation, CPU usage, and other metrics.
There are many profilers available, including:
Application Performance Management (APM) tools go a step further, providing in-depth, real-time insights into an applications performance, availability, and user experience. APM tools can identify performance bottlenecks in real-world scenarios, not just in development and testing.
Asynchronous programming is a way to improve the overall throughput of your application on a single machine. It works by freeing up a thread while waiting for some IO-bound operation (such as a call to an external service or a database) to complete, rather than blocking the thread until the operation is done. When the operation is complete, the framework automatically assigns a thread to continue the execution.
The result is that your application can handle more requests with the same number of threads, as those threads can be used to serve other requests while waiting for IO-bound operations to complete.
ASP.NET Core is built from the ground up to support asynchronous programming. The framework and its underlying I/O libraries are asynchronous to provide maximum performance.
Heres how you might write an asynchronous action in an ASP.NET Core controller:
In this example, GetDataAsync might be making a call to a database or an external service. By awaiting this method, the thread executing this action can be freed up to handle another request.
Heres an example of how you might use async in a service that calls Entity Framework Core:
public MyService(MyDbContext context){_context = context;}
public async Task GetDataAsync(){return await _context.MyData.OrderBy(d => d.Created).FirstOrDefaultAsync();}}
Caching is an effective way to boost the performance of your ASP.NET Core applications. The basic idea is simple: instead of executing a time-consuming operation (like a complex database query) every time you need the result, execute it once, cache the result, and then just retrieve the cached result whenever you need it.
ASP.NET Core provides several built-in ways to cache data:
In-memory caching is the simplest form of caching. It stores data in the memory of the web server. This makes accessing the cached data extremely fast.
In-memory caching in ASP.NET Core stores cache data in the memory of the web server. The data is stored as key-value pairs and can be any object. The access to the in-memory cache is extremely fast, making it an efficient way to store data thats accessed frequently.
One thing to note about in-memory caching is that the cache data is not shared across multiple instances of the application. If you run your application on multiple servers, or if you use a process-per-request model, then the in-memory cache will be separate for each instance or process.
In-memory caching can be an effective way to improve the performance of your application in the following scenarios:
Heres an example of how you might use in-memory caching in an ASP.NET Core controller:
public MyController(IMemoryCache cache){_cache = cache;}
public IActionResult Index(){string cacheEntry;
if (!_cache.TryGetValue("_MyKey", out cacheEntry)) // Look for cache key.{// Key not in cache, so get data.cacheEntry = GetMyData();
// Set cache options.var cacheEntryOptions = new MemoryCacheEntryOptions()// Keep in cache for this time, reset time if accessed..SetSlidingExpiration(TimeSpan.FromMinutes(2));
// Save data in cache._cache.Set("_MyKey", cacheEntry, cacheEntryOptions);}
return View(cacheEntry);}
private string GetMyData(){// Simulating a time-consuming operationThread.Sleep(2000);return "Hello, world!";}}
In this example, the GetMyData method simulates a time-consuming operation. This could be a complex database query, a call to an external service, or any operation that takes time to execute. By caching the result, we avoid the need to execute this operation every time the Index action is called.
Distributed caching involves using a cache thats shared by multiple instances of an application. ASP.NET Core supports several distributed cache stores, including SQL Server, Redis, and NCache.
When using a distributed cache, an instance of your application can read and write data to the cache. Other instances can then read this data from the cache, even if theyre running on different servers.
You should consider using distributed caching in the following scenarios:
When we talk about improving the performance of web applications, one area often overlooked is the size of the HTTP responses. Large responses take longer to transmit over the network, and this latency can have a significant impact on performance, especially for clients with slow network connections.
Response compression is a simple and effective way to reduce the size of HTTP responses, thereby improving the performance of your application. It works by compressing the response data on the server before sending it to the client. The client then decompresses the data before processing it. This process is transparent to the end user.
The most common compression algorithms used for response compression are Gzip and Brotli. They can significantly reduce the size of responses, often by 70% or more.
ASP.NET Core includes middleware for response compression. To enable it, you need to add the middleware to your Startup.ConfigureServices and Startup.Configure methods, like this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){app.UseResponseCompression();
// Other middleware...}
By default, the response compression middleware compresses responses for compressible MIME types (like text, JSON, and SVG). You can add additional MIME types if necessary.
You should also configure your server (like IIS, Kestrel, or HTTP.sys) to use dynamic compression. This ensures that your responses are compressed even if youre not using the response compression middleware (for example, for static files).
While response compression can improve performance, there are a few things to keep in mind:
Entity Framework Core (EF Core) is a powerful Object-Relational Mapper (ORM) that simplifies data access in your .NET applications. However, if used without consideration for its performance behavior, you can end up with an inefficient application. Here are some techniques to improve the performance of your applications that use EF Core:
Lazy loading is a concept where the related data is only loaded from the database when its actually needed. On the other hand, Eager loading means that the related data is loaded from the database as part of the initial query.
While lazy loading can seem convenient, it can result in performance issues due to the N+1 problem, where the application executes an additional query for each entity retrieved. This can result in many round-trips to the database, which increases latency.
Eager loading, where you load all the data you need for a particular operation in one query using the Include method, can often result in more efficient database access. Here's an example:
In this example, each Order and its related Customer are loaded in a single query.
When you query data, EF Core automatically tracks changes to that data. This allows you to update the data and persist those changes back to the database. However, this change tracking requires additional memory and CPU time.
If youre retrieving data that you dont need to update, you can use the AsNoTracking method to tell EF Core not to track changes. This can result in significant performance improvements for read-only operations.
EF Core 5.0 and above support batch operations, meaning it can execute multiple Create, Update, and Delete operations in a single round-trip to the database. This can significantly improve performance when modifying multiple entities.
In this example, all the new orders are sent to the database in a single command, rather than one command per order.
Try to filter data at the database level rather than in-memory to reduce the amount of data transferred and memory used. Use LINQ to create a query that the database can execute, rather than filtering the data after its been retrieved.
In this example, only the orders from the last seven days are retrieved from the database.
The Select N+1 issue is a common performance problem where an application executes N additional SQL queries to fetch the same data that could have been retrieved in just 1 query. EF Cores Include and ThenInclude methods can be used to resolve these issues.
This query retrieves all orders, their related Customers, and the Addresses of the Customers in a single query.
When your application needs to interact with a database, it opens a connection to the database, performs the operation, and then closes the connection. Opening and closing database connections are resource-intensive operations and can take a significant amount of time.
Connection pooling is a technique that can help mitigate this overhead. It works by keeping a pool of active database connections. When your application needs to interact with the database, it borrows a connection from the pool, performs the operation, and then returns the connection to the pool. This way, the overhead of opening and closing connections is incurred less frequently.
Connection pooling is automatically handled by the .NET Core data providers. For example, if you are using SQL Server, the SqlConnection object automatically pools connections for you.
When you create a new SqlConnection and call Open, it checks whether there's an available connection in the pool. If there is, it uses that connection. If not, it opens a new connection. When you call Close on the SqlConnection, the connection is returned to the pool, ready to be used again.
You can control the behavior of the connection pool using the connection string. For example, you can set the Max Pool Size and Min Pool Size options to control the size of the pool.
Optimizing the performance of your ASP.NET Core applications can be a challenging task, especially when youre dealing with complex, data-rich applications. However, with the right strategies and tools at your disposal, its a task thats well within your reach.
In this article, weve explored several key strategies for performance optimization, including understanding performance bottlenecks, leveraging asynchronous programming, utilizing different types of caching, compressing responses, optimizing Entity Framework Core usage, and taking advantage of advanced features such as connection pooling and HTTP/2.
The key takeaway here is that performance optimization is not a one-time event, but a continuous process that involves monitoring, analysis, and iterative improvement. Always be on the lookout for potential bottlenecks, and remember that sometimes the smallest changes can have the biggest impact.
Moreover, while we focused on ASP.NET Core, many of these principles and techniques apply to web development in general. So, even if youre working in a different framework or language, dont hesitate to apply these strategies. The ultimate goal of performance optimization is to provide a smooth, seamless experience for your users.
Happy coding, and heres to fast, efficient applications!
Original post:
Turbocharging ASP.NET Core Applications: A Deep Dive into ... - Medium
Read More..