This article suggests a few tips to improve the performance of an ASP.NET application. There are many more things which may ensure a better performance and faster response time for a web application. I am discussing only a few of the best practices that will help you avoid some unwanted performance hitters from your application. So, you will have a more lightweight application which runs quicker and gives a better response time.
Use Caching
Caching is a good technique to improve your application’s performance. If your application has infrequent data changes or the application has more static content of web page, you can use caching. If your application does not mandate near real-time content to be delivered, consider using output caching. But, the data won’t be the latest for the duration mentioned while enabling caching.
When using caching, what it does is - it stores the output of the page. So, the subsequent requests for the page are loaded immediately by serving this output instead of generating the output. This output is served for the certain period mentioned while enabling caching.
You can cache entire page or fragments of pages or controls depending on the type of static data you have.
Disable View State if Possible
View State is a technique used by an ASP.NET to persist changes to the state of a web form across postbacks to retain the current data for a web application which is otherwise stateless. But View State increases the load of the page both when requested and served. There is also an additional overhead of serializing and de-serializing view state data as it is posted back. View State increases the memory allocations on the server as well.
We can disable the View State of the pages where there is no postback required. This is applicable for controls as well. By default, View State is turned on for all pages and controls. So, turn it off for a page or a control wherever it is not required.
- Disable view state for a single page,
<%@ Page EnableViewState="false" %>
- Disable view state for a single control on a page,
Set EnableViewState = "false"
Set debug=false
When you create the application, debug attribute will be set to "true" by default since it is very useful during development. But, always set debug="false" before deployment. This is a very small thing you need to do but will have a greater impact on the application performance.
Please
click here to refer Scott Guthrie's blog for detailed information.
Avoid Unnecessary Round Trips to Server
Round trips to server significantly affect performance. This is because the requests and responses are created and transferred to server and client. It also takes some time for the server to do the processing and object creation before the response is sent back. Adding to this, sometimes other factors, such as a server is busy with too many requests, network latency etc., can further affect the speed. So, keep round trips to an absolute minimum. How it can be done in each case may depend on your application. A few examples are:
- Use Ajax UI whenever possible
- Do user input validation on the client side using JavaScript
- Avoid unnecessary database hits to load the unchanged content in the database
- Use IsPostBack property
Use Specific CSS and Script files
Using large CSS files that are used for the entire site in multiple pages will increase the loading time of the page thus leading to a performance hit. It can be split and stored in different files thus loading only what is required for each page. It will minimize the loading time of the pages.
For example,
contactus.css can be used for ContactUs.aspx and home.css can be used for Home.aspx, The same way you can split your JavaScript files as well.
Use Paging
Take advantage of paging's simplicity in .net. Loading a large number of records into the server data controls like GridView, DataGrid, and ListView etc. will take a lot of time for the page to load. But, if we show only small subsets of data at a time, the page will load faster. On click of Next button, Previous button or on the page number, you can load the next page of data.
Use String builder to concatenate strings
Use String instead of StringBuilder when you must modify or concatenate a string several times. A string is immutable while StringBuilder is mutable. You cannot change immutable objects after it was created. Any operation that intended to change it, will return a new instance.
For example, the following code creates 2003 instances of string object.
On the otherhand, the code with StringBuilder puts much less stress on memory allocator as it is creating only one instance and modifying it.
- string numbers = "{";
- for (int counter = 0; counter < 1000; counter++) {
- numbers += counter.ToString() + ", ";
- }
- numbers = numbers.Trim(',', ');
- numbers += "}";
- StringBuilder numbers = new StringBuilder("{");
- for (int counter = 0; counter < 1000; counter++) {
- numbers.Append(counter);
- numbers.Append(", ");
- }
- numbers = numbers.Remove(numbers.Length - 2, 2);
- numbers.Append("}");
It doesn't mean it is bad to use Strings, rather it is useful in may circumstances. For example, instances of immutable types are inherently thread-safe, since no thread can modify it. Just avoid using them when you want to modify the string several times.
Use Server.Transfer instead of Response.Redirect for any transfers within your server
Both Server.Transer and Response.Redirect present the user with the contents of a new page but in different ways. When we use Response.Redirect, the server sends an HTTP header back to the browser with an HTTP status code stating that the address of the object has changed along with the new location to find it. The browser then initiates another request to the new object.
On the other hand, Server.Transfer just transfers execution from one page to another page on the server. In effect, back-and-forth network traffic is reduced which therefore eases the pressure on your Web server and network bandwidth and makes your applications run faster.
Use Threads
Threading can help an application run faster, provided you handle it with care. Otherwise, it may cause more problems for you.
You can consider using processor intensive operations and IO operations in a background worker process, or in a separate thread. While one thread running one operation, another thread can work on another operation. This will make your application more responsive.
Now, we have multi-core processors available but many applications are not exploiting the benefits of them. Starting from .NET 4.0, we can use Task Parallel Library to exploit the benefits of parallelism.
Make your page asynchronous
From .NET 4.5 onwards, we have async and await keywords available which helps write asynchronous code more easily. So, try to use the potential of it. We can write asynchronous methods when there are tasks that can be done asynchronously. It will make your application more responsive.
Suppose, a method makes an API call and other unrelated tasks. If you make the method asynchronous by adding an async keyword, after the API call is made, the method executes rest of the code and comebacks when the API result s ready.
Use Stored Procedures
Use Stored Procedures to avoid multiple database hits and get many things done on a single hit. Also, there is a slight performance benefit for the stored procedure over queries as Store Procedures are compiled and stored in the SQL database server, unlike the queries which require compilation. If you are using really long queries and if you change it to SP, the advantage will be more obvious. Because for sending really long queries over the network, more bandwidth need to be used unlike and SP will take only a short line.
Use Images Properly
Reduce the use of images as it will take more time to load and will cause the application to load slowly. Better use very small images in the sense that, ones with less size and get it repeated using CSS. If possible, remove some images and use CSS to give colors, shades, and styles.
Use CSS Layouts
Try to use CSS layouts instead of heavy server controls or HTML table elements wherever possible. For example, we can use <div> elements controlled by CSS to create a table and it will be lightweight and will be easier to manage. A table should be used only to show tabular data.
Set build action to Release
Always remember to take the build in release mode instead of debug mode. Since building mode adds a pdb file for each dll and this will cause your application size to increase and execution time to increase. This is because the debug information are checked before executing code in these assemblies.
For beginners, this is how you set build action to release mode:
Minimise the use of unmanaged Assemblies
Usage of unmanaged assemblies can be a costlier business at times. It is better to avoid the use of unmanaged DLL's if possible. Since, CLR has no control over the calls made to such assemblies and you will have to handle the memory clean up.
Be more diligent while declaring variables
You can avoid a lot of unnecessary memory allocation if you are a bit more cautious while declaring variable. A few cases are,
1. Avoid the use of dynamic keyword if it is not necessary
Because, dynamic types cause compiler and Dynamic Language Runtime (DLR) to do more work. This affects performance and it will be more obvious in case if they are used in loops.
2. Move variable declaration closer to usage It is better because you're limiting the scope of the declared variables. And if you declare them outside the loop, their scope will be broader, which means that it will take longer for the garbage collector to free the memory they hold.
Do Minification
In production use the minified versions of javascript and css files. For the free javascript and css libraries, they will provide a minimied version, just juse the min.js instead of .js. Minify even your custom js and css files before moving to production to reduce the size of the pages.
Do Bundling
Microsoft introduced bundling in ASP.NET 4.5 framework. It makes it easy to combine or bundle multiple files into a single file. A bundle may contain many files and a single request is enough to bring all the code in the bundled files. When you use bundling it also minifies the content by removing extra space.
The benefits we get is temendous with bundling and minification. Please check the Microsoft docs for further details,
https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification
Use CDN
Content Delivery Network (CDN) provide another way of increasing performance. A CDN is a network of servers (nodes) spread across the world. When the application request for a resource from CDN, the content is delivered from a node which is geographically nearest to the user ensuring a faster response time.