10 Best Practices to Improve ASP.Net Core Performance1
Talking Tech

10 Best Practices to Improve ASP.Net Core Performance

Performance, undoubtedly an important part of any web application.

If you look around the internet, there are thousands of websites and apps having similar functions but not all of them are competent enough.

ASP.NET Core is a framework that provides developers a stable foundation for building web applications. However, it is important to perform timely checks to ensure your application is performing up to the mark! Hence, in this blog, we have come up with some really important tips to help improve the performance of your ASP.NET Core applications.

1. Use the Latest Version

Each version comes with a new upgrade, advanced features, and better performance. 

For example, .NET Core 2.1 added JIT compiler, support from compiled regular expressions, and benefitted Span <T> tags, whereas 2.2 have support for HTTP/2. ASP.NET Core 3.0 offered fast memory reading and writing, assembly unloads ability, and more. The latest version of .NET, i.e., .Net 5 is intended to release in November 2020 with simplified processing and optimized performance capabilities.

So, while creating applications using ASP.NET core, always prefer the latest version of the ASP.NET Core as Microsoft always enhances the performance of the latest version in comparison to the previous.

2. Avoid Blocking Calls

You should design you ASP.NET Core application to execute multiple processes simultaneously. And you can achieve this through an Asynchronous API that handles thousands of requests without waiting on blocking calls. Rather than waiting on the synchronous task to complete, it can start working on another thread.

The problem with ASP.NET Core applications is blocking asynchronous execution by calling Task.Wait or Task.Result. These block the thread until the task is completed and wait for its completion. Also, avoid calling Task.Run as ASP.NET Core already runs threads in the normal thread pool so calling Task.Run would result in extra unnecessary Thread Pool Scheduling.

Instead, make hot code paths asynchronous, call data access, I/O, and long-running patterns APIs asynchronously so that operations can be performed without affecting other processes.

You can use Profiler such as PerfView to find the threads frequently added to the Thread Pool.

3. Use Cache

If you want to increase the performance of the application, the commonly known trick is to reduce the number of requests sent to the server every time. How it works: a call is sent to the server and the response received is stored. So, when the next time a call is made for a similar response, instead of requesting the server, the data gets checked with the stored data and if it matches, the data is retrieved from there rather than making a call to the server. 

This is how caching saves time and improves the overall performance; reducing the server calls again and again. You can do client-side, server-side, or client/server-side caching. ASP.NET Core provides different caching such as caching In-Memory, Response caching, Distributed caching, etc.

Always use it for better performance!

4. Optimize Data Access

To improve the performance of the application, we can optimize the data access logic. As the data is fetched from the database, fetching it every time is time-consuming. Here are some techniques that you can use to increase app performance.

  • Reduce the number of HTTP calls i.e. the number of network round trips. 
  • Instead of making multiple calls to the server, try fetching the data in one or two calls.
  • Set a cache for unchanged data. 
  • Do not retrieve the data in advance, if not required. It increases the load on the response and thus application slows down. 

5. Optimize Custom Code

Optimizing code and business logic helps in improving the performance of the applications. Here’s how what you can do

  • Optimize custom logging, authentication, or some custom handler code that executes on every request. 
  • Avoid performing long-running custom executions in the logic layer or middleware as it blocks the request to the server, thus increasing the data fetching time for the application. Instead, you can optimize code either at the client-side or server-side.
  • Perform long-running tasks asynchronously so that other tasks are not affected. 
  • Take real-time client-server communication as SignalR which works asynchronously. 

6. Use Response Caching Middleware

Make your code fast by using Middleware components that optimize frequently-called code paths and store responses and serve them from the cache. The component is available in the Microsoft.AspNetCore.ResponseCaching package. 

In Startup.ConfigureServices, add the Response Caching Middleware to the service collection.

public void ConfigureServices(IServiceCollection services)

{

    services.AddResponseCaching();

    services.AddRazorPages();

}

It is recommended to use performance profiling tools such as PerfView to identify hot code paths.

7. Minimize Large Object Allocations

Though the. Net Core garbage collector manages all the allocations and release of memory automatically in the ASP. NET Core application, cleaning up unreferenced objects takes CPU time. Thus, developers should avoid allocating unwanted objects in the hot code paths. Garbage collection is expensive and large heap generations such as generation 2 require a temporary suspension of app execution to clean up. Frequent allocation and clean up can hamper the app’s performance. 

Tips:

  • Consider caching large objects as it prevents expensive allocations.
  • Use an ArrayPool<T> to store large arrays. 
  • Avoid allocating unnecessary large objects on hot code paths.

8. Use JSON Serialization

.NET Core 3.0 uses System.Text.Json for JSON serialization. That means you can read and write JSON asynchronously without waiting for other processes to execute. Use JSON as it improves the performance better than Newtonsoft.Json. Moreover, the System.Text.Json namespace provides high performance, low allocation, compliant capabilities, objects to JSON text serialization, and deserialization of JSON text to objects.

9. Use Response Compression

Compressing file size is another factor in improving performance. Response compression compresses the file size and in ASP.NET Core it’s available as a middleware component. Usually, responses are not natively compressed. This typically includes CSS, JavaScript, HTML, XML, and JSON.

  • Don’t compress natively compressed assets, such as PNG files.
  • Don’t compress files smaller than about 150-1000 bytes

10. Minimize Exceptions

Throwing and catching exceptions is slower than other code patterns. Hence, they should be rare and shouldn’t be used to control normal program flow.

Tips:

  • Add code logic to detect and handle conditions that cause exceptions. 
  • Add a throw or catch exceptions for unusual or unexpected conditions.

You can use App diagnostic tools such as Application Insights to identify common exceptions in an app and how they perform. 

Bonus Tips to Improve Performance

  • Prefer ReadFormAsync over Request.Form
  • Do not store IHttpContextAccessor.HttpContext in a field
  • Do not access HttpContext from multiple threads as it’s not safe and can result in undefined behavior such as hangs, crashes, and data corruption.
  • Do not capture services injected into the controllers on background threads
  • Do not modify the status code or headers after the response body has started as ASP.NET Core doesn’t buffer the HTTP response body.

Client-Side Improvements

  • Bundling and Minification

Optimize the content before loading using minification. Minimize the code and try to load all your client-side assets like JS/CSS in one go. After minifying the files, bundle those in one so that it can be loaded faster. Just like the zip file. Compress it and then zip it.

  • Load JavaScript at Last

Always load the JavaScript files at last. Because this way, your website gets rendered in minimum time and when JavaScript executes, DOM elements are already present. Thus, the application can be made faster. 

  • Shrink Images

Large images take a lot of time to load. Instead, you can shrink the images using compression tools to improve loading time. 

  • Use CDN

If you are using third-party libraries for CSS and JavaScript which have CDN version available, then try using the CDN file path rather than downloaded library file. CDN has different servers across different zones, and if you are using a website in one zone, you will get the CDN file from the server while accessing the website and that is faster than self-loading of the huge library file. 

Conclusion

These 10 tips along with the bonus ones will help you improve the performance of ASP.NET Core applications. Try to implement most of them in your ASP.NET Core app development.

To know more about ASP.NET Core development or some hacks, contact us!