Performance is very important; it is a major factor for the success of any web application. ASP.NET Core 3.0 includes several enhancements that scale back memory usage and improve turnout. The following is 10 tips to increase your ASP.NET Core performance:
1. Avoid synchronous and use asynchronous
Try to avoid synchronous calling when developing ASP.NET Core 3.0 applications. Synchronous calling blocks the next execution until the current execution is completed. While fetching data from an API or performing operations like I/O operations or independent calling, execute the call in an asynchronous manner.
Avoid using Task.Wait and Task.Result, and try to use await. The following code shows how to do this.
public
class
WebHost
{
public
virtual
async
Task StartAsync(CancellationToken cancellationToken =
default
)
{
// Fire IHostedService.Start
await
_hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(
false
);
// More setup
await
Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(
false
);
// Fire IApplicationLifetime.Started
_applicationLifetime?.NotifyStarted();
// Remaining setup
}
}
2. Asynchronous saving
Asynchronous saving avoids a thread block while changes are written to the database. It provides DbContext.SaveChangesAsync() as an asynchronous alternative to DbContext.SaveChanges().
public
static
async
Task AddBlogAsync(
string
url)
{
using
(
var
context =
new
BloggingContext())
{
var
blogContent =
new
BlogContent { Url = url };
context.Blogs.Add(blogContent);
await
context.SaveChangesAsync();
}
}
3. Use caching technology
Increase the performance of an application by reducing the number of requests to the server. Avoid calling the server every time and cache the data instead. Store the response for the future, and use it the next time you make a call for the same response.
These are some caching techniques:
- In-memory caching.
- Distributed cache.
- Cache tag helper.
- Distributed cache tag helper.
4. Asynchronous querying
Asynchronous queries avoid blocking a thread while the query is executed in the database. Async queries are important for quick, responsive client applications.
Examples:
- ToListAsync()
- ToArrayAsync()
- SingleAsync()
public
async
Task<List> GetBlogsAsync()
{
using
(
var
context =
new
BloggingContext())
{
return
await
context.Blogs.ToListAsync();
}
}
5. Use JSON serialization
ASP.NET Core 3.0 uses System.Text.Json for JSON serialization by default. Now, you can read and write JSON asynchronously. This improves performance better than Newtonsoft.Json. The System.Text.Json namespace provides the following features for processing JSON:
- High performance.
- Low allocation.
- Standards-compliant capabilities.
- Serializing objects to JSON text and deserializing JSON text to objects.
6. Use response compression
Response compression, which compresses the size of a file, is another factor in improving performance. In ASP.NET Core, response compression is 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
The following sample code shows how to enable Response Compression Middleware for the default MIME types and compression providers.
public
class
Startup
{
public
void
ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
}
public
void
Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCompression();
}
}
These are the providers:
public
void
ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<CustomCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new
[] {
"image/svg+xml"
});
});
}
7. HttpContext accessibility improvements
HttpContext accessibility is only valid as long as there is an active HTTP request in ASP.NET Core. Here are some suggestions for accessing HttpContext from Microsoft’s documentation:
- Don’t store IHttpContextAccessor.HttpContext in a field.
- Don’t access HttpContext from multiple threads.
- Don’t use the HttpContext after the request is complete
- Don’t capture the HttpContext in background threads
8. Reduce HTTP requests
Reducing the number of HTTP requests is one of the major optimizations. Cache the webpages and avoid client-side redirects to reduce the number of connections made to the web server.
Use the following techniques to reduce the HTTP requests:
- Use minification.
- Use bundling.
- Use sprite images.
By reducing HTTP requests, these techniques help pages load faster.
9. Use exceptions only when necessary
Exceptions should be rare. Throwing and catching exceptions will consume more time relative to other code flow patterns.
- Don’t throw and catch exceptions in normal program flow.
- Use exceptions only when they are needed.
10. Client-side improvements
Client-side optimization is one important aspect of improving performance. When creating a website using ASP.Net Core, consider the following tips:
Bundling
Bundling combines multiple files into a single file, reducing the number of server requests. You can use multiple individual bundles in a webpage.
Minification
Minification removes unnecessary characters from code without changing any functionality, also reducing file size. After applying minification, variable names are shortened to one character and comments and unnecessary whitespace are removed.
Loading JavaScript at last
Load JavaScript files at the end. If you do that, static content will show faster, so users won’t have to wait to see the content.
Use a content delivery network
Use a content delivery network (CDN) to load static files such as images, JS, CSS, etc. This keeps your data close to your consumers, serving it from the nearest local server.
Conclusion
Hope that tips above can help you to improve your ASP.NET Core 3.0 performance. If you have other feedback, please kindly let us know. Thank you!
Andriy Kravets is writer and experience .NET developer and like .NET for regular development. He likes to build cross-platform libraries/software with .NET.