10 Best Practices to Improve ASP.Net Core Performance

Nikita Rohira

By : Nikita Rohira

10 Best Practices to Improve ASP.Net Core Performance1

There is one major reason, why ASP.NET core is a favourite framework for everyone — Its Performance

It provides developers a stable foundation for building web applications. However, it is important for ASP.Net developers to adopt smart development practices to ensure robust and secure software is built. In addition, they have to perform timely checks to ensure the application is performing up to the mark.

This blog is all about some important tips to improve the performance of your ASP.NET Core applications.

Why ASP.NET Core is the best?

Backed by Microsoft, ASP.Net core brings the benefits of ASP.NET and MVC.NET in a common programming paradigm. Its high security and exclusive features make it an excellent choice for developing quality web applications.

Here, look at some of the reasons why ASP.Net is considered one of the best technologies present today.

  • Asynchronous programming model
    With asynchronous programming model used in ASP.Net core, you can save your valuable time and resource effortlessly. It eliminates any need for CPUs to wait for web service calls, database queries, I/O operations, etc. Thus, your processes become much faster.
  • Scalability and security
    The server-side web app framework is popularly known for its impeccable security and has become ythe perfect choice for enterprises. It extends several built-in and third-party libraries and tools to protect the security of web applications.
    ASP.Net core comes with features like HTTPS enforcement, data protection, anti-request foregery protection, app secrets, CORS management, and seamless authentication and authorization management.
    Furthermore, it is highly scalable because of distributed cache and can be used by businesses of all sizes.
  • Hybrid app development support
    ASP.Net core is built to be modular and is capable of developing hybrid apps suitable for windows and web. So, if you need to develop a hybrid app with complete security and scalability, ASP.Net core is for you.
  • Easy deployment, integration, & maintenance
    The portable and lightweight ASP.Net core provides you the flexibility to work with multiple libraries, tools, amd programming languages. Thus, it becomes much easier for developers to integrate third-party libraries, develop, deploy, and maintain ASP.Net core applications.
  • Open-source
    ASP.Net core is an open-source framework and can be used by anyone and everyone free of cost. Since you don’t have to oay anything for the software, you can save a lot on development costs. Besides, you also get to connect with the ASP.Net core community for any development issues and queries.
    The cross-platform framework is evidently one of the most flexible and secure technology present today. It is capable of developing web applications that run flawlessly on Mac, Windows, and Linux operating systems.

Best Development Practices to Adhere for Efficient 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 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. As for ASP.Net core 5, they introduced new features like Text.JSON, C#9 record type support and improvements in MVC model binding & Visual basics.

The latest version of .NET, i.e., .Net 6 Core was released on November 8, 2021 with simplified processing and optimized performance capabilities. With features like hot reloading, smart code editing, support for Visual Studio 2022, developing full-stack software is made effortless.

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.

Ensuring technicalities of a running application could be a tedious task. AT Biztech, we have a team of experienced developers that could be your extended team to manage your tasks. Whether you want to build the app from scratch or want customization in your current app, get in touch with us today for the best possible solutions.

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

One of the many benefits of Asp.Net Core is the availability of garbale collector to manage all allocations, release memory automatically in the ASP. NET Core applications, and cleaning up unreferenced objects that 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.

Our team has an extensive experience of working with Asp.Net apps, At Biztech, we have a strong portfolio of clients that have been with us for years. Get in touch with us for your ASP.NET app requirements!

8. Use JSON Serialization

ASP.NET Core 6.0 utilizes ‘System.Text.Json’ for JSON serialization to and deserialization from options. 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. Now, instead of serializing vis string-based methods, you can serialize using an UTF-8 array. This method is near about 5 to 10% faster in execution. You need to call JsonSerializer.SerializeToUtf8Bytes method for the serialization.

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.
  • It is advisable to use developer-friendly & easy to customize Asp NET Dashboard for building a responsive web app.

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

I hope the information above helps you improve the performance of your ASP.NET Core applications. Try to implement most of them in your app development to leverage the multiple benefits of Asp.Net core. If you have any challenges while making changes our expert team can help you with solutions.

After working for over a decade with clients like you, ASP.NET core is one of our forte with a strong portfolio.Our seasoned ASP.Net developers can handle every challenge and build robust applications that streamlines with your business goals.

Let’s get in touch today with your requirements.

FAQs

How to improve the performance of ASP.NET Core?

To improve the performance of ASP.Net core, invest in best development practices such as avoiding blocking calls, caching, minimizing large object allocations, optimizing I/O and data access, minimize exceptions, and compress responses, etc.

Is ASP.NET Core faster than node JS?

The built-in IIS server kernel caching in ASP.Net core makes the process of CPU rendering much more simpler here. Thus, even if your application performs CPU-intensive tasks, ASP.Net core is capable of performing much faster compared to Node JS.

Which is better ASP.NET or ASP.NET Core?

Both are based on MVC (Model, View, Controller) architecture and perform seamlessly. However, the support for modular architecture and robust cloud support makes ASP.Net core a preferable choice in many occasions.

Get a Free Consultation

    ✓ 100% Guaranteed Security of Your Information