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
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
- Setting up a Virtual Server on Ninefold - Video [Last Updated On: February 26th, 2012] [Originally Added On: February 26th, 2012]
- ScaleXtreme Automates Cloud-Based Patch Management For Virtual, Physical Servers [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- Secure Cloud Computing Software manages IT resources. [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- Dell unveils new servers, says not a PC company [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- Wyse to Launch Client Infrastructure Management Software as a Service, Enabling Simple and Secure Management of Any ... [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- As the App Culture Builds, Dell Accelerates its Shift to Services with New Line of Servers, Flash Capabilities [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- Terraria - Cloud In A Ballon - Video [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- Ethernet Alliance Interoperability Demo Showcases High-Speed Cloud Connections [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- RSA and Zscaler Teaming Up to Deliver Trusted Access for Cloud Computing [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- [NEC Report from MWC2012] NEC-Cloud-Marketplace - Video [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- IBM SmartCloud Virtualized Server Recovery - Video [Last Updated On: February 28th, 2012] [Originally Added On: February 28th, 2012]
- BeyondTrust Launches PowerBroker Servers Windows Edition [Last Updated On: February 29th, 2012] [Originally Added On: February 29th, 2012]
- Ericsson joins OpenStack cloud infrastructure community [Last Updated On: February 29th, 2012] [Originally Added On: February 29th, 2012]
- ScaleXtreme Cloud-Based Patch Management Open for New Customers [Last Updated On: March 1st, 2012] [Originally Added On: March 1st, 2012]
- RootAxcess - Getting Started - Video [Last Updated On: March 1st, 2012] [Originally Added On: March 1st, 2012]
- How to Create a Terraria Server 1.1.2 (All Links Provided) - Video [Last Updated On: March 1st, 2012] [Originally Added On: March 1st, 2012]
- Dell #1 in Hyperscale Servers (Steve Cumings) - Video [Last Updated On: March 1st, 2012] [Originally Added On: March 1st, 2012]
- Managing SAP on Power Systems with Cloud technologies delivers superior IT economics - Video [Last Updated On: March 1st, 2012] [Originally Added On: March 1st, 2012]
- AMD Acquires Cloud Server Maker SeaMicro for $334M USD [Last Updated On: March 3rd, 2012] [Originally Added On: March 3rd, 2012]
- Web Host 1&1 Provides More Flexibility with Dynamic Cloud Server [Last Updated On: March 3rd, 2012] [Originally Added On: March 3rd, 2012]
- Leap Day brings down Microsoft's Azure cloud service [Last Updated On: March 3rd, 2012] [Originally Added On: March 3rd, 2012]
- RightMobileApps White Label Program - Video [Last Updated On: March 3rd, 2012] [Originally Added On: March 3rd, 2012]
- bzst server ban #2 - Video [Last Updated On: March 3rd, 2012] [Originally Added On: March 3rd, 2012]
- “Cloud storage served from an array would cost $2 a gigabyte” [Last Updated On: March 6th, 2012] [Originally Added On: March 6th, 2012]
- More Flexibility with the 1&1 Dynamic Cloud Server [Last Updated On: March 6th, 2012] [Originally Added On: March 6th, 2012]
- Hub’s future jobs may be in cloud [Last Updated On: March 6th, 2012] [Originally Added On: March 6th, 2012]
- Cloud computing growing jobs, says Microsoft [Last Updated On: March 6th, 2012] [Originally Added On: March 6th, 2012]
- TurnKey Internet Launches WebMatrix, a New Application in Partnership with Microsoft [Last Updated On: March 6th, 2012] [Originally Added On: March 6th, 2012]
- Cebit 2012: SAP Cloud Computing Strategy - Introduction - Video [Last Updated On: March 6th, 2012] [Originally Added On: March 6th, 2012]
- Dome9 Security Launches Industry's First Free Cloud Security for Unlimited Number of Servers [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- Servers Are Refreshed With Intel's New E5 Chips [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- Samsung's AllShare Play pushes pictures from phone to cloud and TV [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- Google drops the price of Cloud Storage service [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- New Intel Server Technology: Powering the Cloud to Handle 15 Billion Connected Devices [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- Swisscom IT Services Launches Cloud Storage Services Powered by CTERA Networks [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- KineticD Releases Suite of Cloud Backup Offerings for SMBs [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- First Look: Samsung Allshare Play - Video [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- Bill The Server Guy Introduces the New Intel XEON e5-2600 (Romley) Server CPU's - Video [Last Updated On: March 7th, 2012] [Originally Added On: March 7th, 2012]
- New Cisco servers have Intel Xeon E5 inside [Last Updated On: March 8th, 2012] [Originally Added On: March 8th, 2012]
- Cisco rolls out UCS servers with Intel Xeon E5 chips [Last Updated On: March 8th, 2012] [Originally Added On: March 8th, 2012]
- From scooters to servers: The best of Launch, Day One [Last Updated On: March 8th, 2012] [Originally Added On: March 8th, 2012]
- Computer Basics: What is the Cloud? - Video [Last Updated On: March 9th, 2012] [Originally Added On: March 9th, 2012]
- Could the digital 'cloud' crash? [Last Updated On: March 10th, 2012] [Originally Added On: March 10th, 2012]
- Dome9 Security Launches Free Cloud Security For Unlimited Number Of Servers [Last Updated On: March 10th, 2012] [Originally Added On: March 10th, 2012]
- Cloud computing 'made in Germany' stirs debate at CeBIT [Last Updated On: March 11th, 2012] [Originally Added On: March 11th, 2012]
- New Key Technology Simplifies Data Encryption in the Cloud [Last Updated On: March 11th, 2012] [Originally Added On: March 11th, 2012]
- Can a private cloud drive energy efficiency in datacentres? [Last Updated On: March 12th, 2012] [Originally Added On: March 12th, 2012]
- Porticor's new key technology simplifies data encryption in the cloud [Last Updated On: March 12th, 2012] [Originally Added On: March 12th, 2012]
- Borders + Gratehouse Adds Three New Clients in Cloud Sector [Last Updated On: March 12th, 2012] [Originally Added On: March 12th, 2012]
- Dell to invest $700 mn in R&D, unveils 12G servers [Last Updated On: March 13th, 2012] [Originally Added On: March 13th, 2012]
- Defiant Kaleidescape To Keep Shipping Movie Servers [Last Updated On: March 13th, 2012] [Originally Added On: March 13th, 2012]
- Data Centre Transformation Master Class 3: Cloud Architecture - Video [Last Updated On: March 13th, 2012] [Originally Added On: March 13th, 2012]
- DotNetNuke Tutorial - Great hosting tool - PowerDNN Control Suite - part 1/3 - Video #310 - Video [Last Updated On: March 13th, 2012] [Originally Added On: March 13th, 2012]
- Cloud Computing - 28/02/12 - Video [Last Updated On: March 13th, 2012] [Originally Added On: March 13th, 2012]
- SYS-CON.tv @ 9th Cloud Expo | Nand Mulchandani, CEO and Co-Founder of ScaleXtreme - Video [Last Updated On: March 13th, 2012] [Originally Added On: March 13th, 2012]
- Oni Launches New Cloud Services for Enterprises Using CA Technologies Cloud Platform [Last Updated On: March 14th, 2012] [Originally Added On: March 14th, 2012]
- SmartStyle Advanced Technology - Video [Last Updated On: March 14th, 2012] [Originally Added On: March 14th, 2012]
- SmartStyle Infrastructure - Video [Last Updated On: March 14th, 2012] [Originally Added On: March 14th, 2012]
- The Hidden Risk of a Meltdown in the Cloud [Last Updated On: March 14th, 2012] [Originally Added On: March 14th, 2012]
- FireHost Launches Secure Cloud Data Center in Phoenix, Arizona [Last Updated On: March 14th, 2012] [Originally Added On: March 14th, 2012]
- Panda Security Launches New Channel Partner Recruitment Campaign: "Security to the Power of the Cloud" [Last Updated On: March 14th, 2012] [Originally Added On: March 14th, 2012]
- NetSTAR, Inc. Announces Safe and Secure Web Browsers for iPhones, iPads, and Android Devices [Last Updated On: March 14th, 2012] [Originally Added On: March 14th, 2012]
- Amazon Cloud Powered by 'Almost 500,000 Servers' [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- NetSTAR Announces Secure Web Browsers For iPhones, iPads, And Android Devices [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- Be Prepared For When the Cloud Really Fails [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- Dr. Cloud explains dinCloud's hosted virtual server solution - Video [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- New estimate pegs Amazon's cloud at nearly half a million servers [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- Amazon’s Web Services Uses 450K Servers [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- Saving File On Internet - Cloud Computing - Video [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- DotNetNuke Tutorial - Great hosting tool - PowerDNN Control Suite - part 2/3 - Video #311 - Video [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- Linux servers keep growing, Windows & Unix keep shrinking [Last Updated On: March 15th, 2012] [Originally Added On: March 15th, 2012]
- Cloud Desktop from Compute Blocks - Video [Last Updated On: March 16th, 2012] [Originally Added On: March 16th, 2012]
- Amazon EC2 cloud is made up of almost half-a-million Linux servers [Last Updated On: March 17th, 2012] [Originally Added On: March 17th, 2012]
- HP trots out new line of “self-sufficient” servers [Last Updated On: March 17th, 2012] [Originally Added On: March 17th, 2012]
- Cloud Web Hosting Reviews - Australian Cloud Hosting Providers - Video [Last Updated On: March 17th, 2012] [Originally Added On: March 17th, 2012]
- Using Porticor to protect data in a snapshot scenario in AWS - Video [Last Updated On: March 17th, 2012] [Originally Added On: March 17th, 2012]
- CDW - Charles Barkley - New Office - Video [Last Updated On: March 17th, 2012] [Originally Added On: March 17th, 2012]
- Nearly a Half Million Servers May Power Amazon Cloud [Last Updated On: March 17th, 2012] [Originally Added On: March 17th, 2012]
- Morphlabs CEO Winston Damarillo talks about their mCloud Rack - Video [Last Updated On: March 20th, 2012] [Originally Added On: March 20th, 2012]
- AMD reaches for the cloud with new server chips [Last Updated On: March 20th, 2012] [Originally Added On: March 20th, 2012]