DEV Community

FacileTechnolab
FacileTechnolab

Posted on • Originally published at faciletechnolab.com on

5 performance improvement tips for asp.net core web applications

Performance is the major factor for success of any web application development. ASP.NET Core is one of the best platforms to build high performance web applications. In this article, I am going to share 5 tips that can help your web application perform better.

5 performance improvement tips for your asp.net core web application

  1. Use asynchronous database operations with entity framework core.
  2. Follow Entity framework core data access best practices.
  3. Monitoring and optimizing queries.
  4. Use caching.
  5. Switch to background processing.

1. Use asynchronous database operations with entity framework core.

The new features of the C# language provide powerful features to implement asynchronous programming using keywords like async and await. The use of asynchronous programming will allow the execution of the code in parallel and do not block the execution while performing heavy I/O operations while connecting to external data sources of the web application.

Entity Framework Core comes up with asynchronous extension methods that can be used to take advantage of asynchronous programming. You can find an asynchronous extension method available now for the majority of the LINQ methods that you use. For example, using DbContext, you do database operations to get data from some table. ToListAsync() method is asynchronous variant of ToList() method for reading data asynchronously. Similarly, SaveChangesAsync() is an asynchronous variant of SaveChanges() method that is available to save data asynchronously.

Switching to asynchronous programming might require little bit of learning but you will get used to it.

Here is an example of the synchronous data access:

public List Posts()
{ 
    return db.Posts.ToList(); 
} 

Enter fullscreen mode Exit fullscreen mode

Which can be re-written to

public async Task> Posts()
{
    return await db.Posts.ToListAsync(); 
} 

Enter fullscreen mode Exit fullscreen mode

Where db is an object of DbContext of your application.

2. Follow Entity Framework Core data access best practices

Every application requires accessing data from the database. Since data access operations directly impact the performance of your web application, here we are sharing some of the most basic Entity Framework Core data access best practices that will require minor code adjustments to get major performance improvements.

  • Project properties you only need – Entity Framework core makes it very easy to query inefficiently. But, you need to make sure you are using Where(), SingleOrDefault() and Select() functions to efficiently retrieve the only amount of data that you need to.
  • Use AsNoTracking() extension method – Entity Framework Core provides AsNoTracking() method that can be used in cases where you want to select and return data without processing. For example, you are listing the items from the database table into the grid. In such cases, use as AsNoTracking() can improve the performance of the code by up to 30% faster.
  • Delay retrieving data until its needed – There are times when data from the database is required in the last but you are loading data at the beginning of the method but due to certain condition statements the method returns without using it. In such cases, delay retrieving data until it’s needed.
  • Use indexing – Majority of databases like Microsoft SQL Server and PostgreSQL supports indexing which can drastically improve the performance of queries that are being executed. Use techniques to find the missing indexes and generate appropriate indexes in the database to ensure highest performance.

3. Monitoring and optimizing queries

Monitoring is the key operation to perform any performance improvement. This is yet another tip that is related to entity framework core and data access in your application where we will talk about how to efficiently set up entity framework core to monitor SQL, statistics, and errors.

Enable logging – Starting Entity Framework Core 5.0, a new feature is introduced called simple logging. It supports a feature that will log SQL statements generated against your LINQ queries and how much time the SQL queries take to execute.


    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.LogTo(Console.WriteLine);  


Enter fullscreen mode Exit fullscreen mode

There are additional configuration options like EnableSensitiveDataLogging, and EnableDetailedErrors which helps review detailed SQL, execution statistics and detailed errors.

4. Use caching

Caching is another technique through which you can drastically improve your web application performance. Depending on the type of web application and data it uses, you can decide your cache strategy which includes:

  • *Type of Caching * – There are various ways you can use cache in web application. In-memory cache where data is stored in application runtime memory. This type of cache is available when your application starts and wiped off once the application is stopped. ASP.NET Core runtime provides in-memory cache which can be configured on application startup and injected in the controller of the application to store and retrieve data from cache.

Distributed cache stores data out of application process and generally available across multiple application instances and persists regardless of the state of the application runtime. Redis is a popular distributed caching solution to the application. Depending on your hosting model, Redis is available as on-premise windows service, docker container, or cloud service.

  • What to cache – There is part of data your web application depends on that hardly changes once persisted. Examples are list of countries, currencies etc. For such kind of data, caching them to the cache and return them from the cache gives the best performance.

There are other use cases like fetching data from external sources and re-structuring them to represent certain reports. If this operation takes place into server and takes lots of time, it can be cached to avoid user wait time and can be refreshed periodically as per requirement.

  • Invalidate cache – This is important aspect of your cache strategy as not invalidating or refreshing the cached data may result in the unexpected behavior. Both, In-memory and distributed caching supports APIs that can be used to remove cache entry or refresh the cache entry.

5. Switch to background processing

There are cases when user request is processed with too many operations that can actually be switched to background in order to improve response time.

A good example is user registration request. A typical application will persist a new user to database, send out some kind of email for verification and then response is returned to the user. This process can be improved by switching the email sending operation to background processing and return response to end user early.

ASP.NET Core supports background operations and there are many other specialist frameworks available in ASP.NET Core like Quartz.Net and Hangfire which can be used for efficient background processing. There are other external frameworks like RabbitMq, Microsoft Msmq, Azure Service Bus, and AWS SQS which are all supports use case of processing data in background with efficient dashboads, scheduling, processing, monitoring and logging facilities.

Conclusion

Now you know at least 5 performance improvement tips for asp.net core web application that you can implement in your next web application.

Discussion (0)