SP Optimization and .Net Tips
SP Optimization and .Net Tips
So, while creating the application using ASP.NET Core, always prefer to use the latest
version of ASP.NET Core. With the latest version, you will definitely find the performance
improvement. Next version of ASP.NET Core is 3.0 which is under development and
hopefully, it will be released very soon with Visual Studio 2019.
You should use end to end Asynchronous Programming while writing the code. Let’s
take one example, we have one ASP.NET Core MVC application with database
implementation. As we know, it could have many separations and it all depends on user
project architecture, but take some simple example where we
have Controller > Repository Layer, etc. Let's see how you will write the sample
code at the controller level.
C#
Copy Code
[HttpGet]
[Route("GetPosts")]
public async Task < IActionResult > GetPosts()
{
try {
var posts = await postRepository.GetPosts();
if (posts == null) {
return NotFound();
}
return Ok(posts);
}
catch (Exception) {
return BadRequest();
}
}
C#
Copy Code
return null;
}
// Good Performance
Task task = DoWork();
await task;
// Bad Performance
Task task = DoWork();
task.Wait();
Let's understand a good and bad example of Task.Result as follows:
C#
Copy Code
// Good Performance on UI
Task < string > task = GetEmployeeName();
txtEmployeeName.Text = await task;
// Bad Performance on UI
Task < string > task = GetEmployeeName();
txtEmployeeName.Text = task.Result;
Know more about Best Practices for Asynchronous Programming.
Keeping the data in that location from where we can get it frequently without making
the call to the server is a good practice. Here, we can use the Cache. Caching the
content helps us to reduce server calls again and again and it helps us to increase the
performance of the application. We can do the cache at any point of a location like on
client-side caching, server-side caching or client/server-side caching.
We have different kinds of caching available in ASP.NET Core like we can do the caching
In-Memory or we can use Response caching or we can use Distributed Caching. More
about Caching in Asp.Net Core.
C#
Copy Code
1. Reduce the number of HTTP calls, means you should always try to reduce the
number of network round trips.
2. Try to get all the data in one go. Means rather than making multiple calls to the
server, just make one or two calls which can bring all required data.
3. Frequently, set the cache on data which is not being changed.
4. Don’t try to get the data in advance which is not required, it will increase the
load on the response and your application will load slower.
But if you write your data access logic in optimize ways in EF Core, then definitely it
improves the performance of the application. Here, we have some of the techniques
which will increase the performance.
1. Use No Tracking while getting the data which is the only read-only purpose. It
improves performance.
2. Try to filter the data on the database side, don’t fetch the whole data using query
and then filter at your end. You can use some function available in EF Core
like Where, Select which help you to filter the data on the database side.
3. Retrieve only the required number of records which is necessary using the help
of Take and Skip. You can take one example of paging where you can
implement Take and Skip while clicking on the page number.
Let's take one example and try to understand how we can optimize the EF Core
query using Select and AsNoTracking.
C#
Copy Code
public async Task < PaginatedList < Post >> GetPagedPendingPosts
(int pageIndex, int pageSize, List<Category> allowedCategories)
{
var allowedCatIds = allowedCategories.Select(x => x.Id);
var query = _context.Post
.Include(x => x.Topic.Category)
.Include(x => x.User)
.Where(x => x.Pending == true &&
allowedCatIds.Contains(x.Topic.Category.Id))
.OrderBy(x => x.DateCreated);
1. Write logic in such a way for the process which is optimized and tested and which
minimizes the exception to be a part of the flow. Less number of chances to
execute the exception code means high performed application.
2. Always try to use simple NET code or highly performed ORM like Dapper for
database operations. It is because if database operations will take much time to
execute the query, then it will decrease the performance of the application. As
we all know, in the development phase, implementing the ADO.NET code and
managing it will take more time as compared to ORM implementation. But this is
also true if you use simple ADO.NET, then your application will be faster than if
you use any other ORM.
3. If response size is large, than obviously it will take much time to load it. So,
always reduce the response size using compression techniques and then load the
data. You can implement the compression logic in middleware. We have some of
the compression providers like Gzip, Brotli.
C#
Copy Code
services.Configure<GzipCompressionProviderOptions>(options => {
options.Level = CompressionLevel.Fastest;
});
}
Bonus Tips (Client Side)
We would like to share some of the performance tips for client-side code. If you are
creating a website using the ASP.NET Core MVC, then I believe you should always follow
these tips to make your website perform well.
Using bundling and minification, we can optimize the content before loading on
UI. From the performance point of view, always try to load all your client-side
assets like JS/CSS in one go. It reduces the number of network hits. You can first
minify your files using minification and then bundle those in one file which can be
loaded faster and reduce the number of an HTTP request for resources.
You should always try to load your JavaScript files at last. We have many benefits
like first of all, your website gets rendered in minimum time and when your
JavaScript will execute, then your DOM elements will be available. Using this, you
can make your application faster.
Shrink Images
Always avoid loading images in maximum size. Before loading, you can shrink
the images using compression techniques.
Use CDN
If you have your custom CSS or JavaScript files, then it’s OK to load it. But if you
are using some third party libraries which have CDN version available, then
always try to use the CDN file path rather than downloaded library file path from
your end. It is because CDN has different servers available on a different zone, if
you are using a website in one zone, then you will get the CDN file from your
zone server when you hit the website, which is very fast.
Edit and Continue is a time-saving feature that enables you to make changes
to your source code while your program is in break mode. When you resume
execution of the program by choosing an execution command
like Continue or Step, Edit and Continue automatically applies the code
changes with some limitations. This allows you to make changes to your
code during a debugging session, instead of having to stop, recompile your
entire program, and restart the debugging session.