ASP.NET Website Performance Improvement Tips

This article gives you some of the best tips to improve your ASP.NET Website performance.

Writing an ASP.NET application is relatively easy with the use of Rapid Application Development controls however it is just not enough to use. You should use each component wisely to get performance benefits to your ASP.NET Website.

Remember that 80-90% of page load time spent on downloading all components like HTML, CSS, Script files, images, flash. Rather than looking for re-designing application architecture, you should first try to organize your static content. Below are some easy tips which help you to achieve a bigger reduction in response time.

HTTP compression

Make sure HTTP compression is turned On. HTTP compression is an algorithm that removes extra space, redundancy from file, and produces clean output. It generates a smaller size and reduces the weight of the file than the original representation. The outcome of this is reduced bandwidth and time to load the page.

Although the support for compression is a feature of all modern browsers you should enable and configure or implement custom compression features.

You can configure httpCompression tag under system.webServer in ASP.NET Web.config file or Enable HttpCompression feature in IIS.

You can also implement HttpModule to remove space and return compressed output. However, it includes runtime cost to implement custom logic to remove unwanted space and redundancy. You can compress your physical files using GZipStream before deploying to production server. Check for more IIS settings to improve ASP.NET Website Performance.

Below is a sample code to compress your aspx file.


private void CompressFile(string srcPath, string tarPath)
{
    using(FileStream srcStream = File.OpenRead(srcPath))
    {
        using(FileStream tarStream = File.OpenWrite(tarPath));
        {
            using(GZipStream cStream = new GZipStream(srcStream,
            CompressMode.Compress))
            {
            byte[]data = new byte[srcStream.Length];
            srcStream.Read(data, 0, data.Length);
            tarStream.Write(data, 0, data.Length);
            }
        }
    }
}
    
            

You may check for more detail way of enable httpCompression for asp.net web sites

Set CacheControlMaxAge

Set CacheControlMaxAge property in Web.config file. It caches static contents like image, CSS, JS files for a particular duration. One year is the recommended setting.

Below Web.config setting shows you how to configure caching for static contents. By configuring this browser will cache static contents till June 30, 2022.


  <system.webServer>
  <staticcontent>
      <clientCache cacheControlMode="UseExpires" 
            httpExpires="Tue, 30 June 2022 03:14:07 GMT"/>
  </staticcontent>
  </system.webServer>
            

Configure MiniProfiler

Get MiniProfiler from GitHub or use Nuget package manager and configure it for your site. It is a profiling library developed by StackExchange team which helps to monitor your Website performance. You can see detailed execution time. Do not give access to end user and once your testing is done remove the configuration.

Data Controls Paging

For your Data controls like GridView, DataGrid, Repeater UI controls, make sure you are using custom or database level paging. The built in feature of control's paging is very heavy and expensive as it has to get all the records (no matter how big is your resultset) from the database and then filter it at the client side as per current page number and page size.

When you implement custom paging you provide required page index and page size to database and database returns filtered rows as per input values. So it reduces the required bandwidth and loading time for GridView. For more details see how to implement custom paging in ASP.NET.

Client side input validations

For rich user experience, it is necessary to validate user input on the client side using JavaScript or jQuery. You can also use RegEx expression to make sure input data is valid format. This provides quick feedback and makes page more responsive. Also you should provide easy to understand error messages to users.

Although client side validations are quick and responsive, do not avoid server side validations as client side validations easy to break.

Reduce data sent across the network

Reducing the amount of data sent across the network can improve your application performance significantly. You can achieve this by below things

1. Combine script and css files: Try to combine all script files in single file, it reduces required number of requests to load the page. If you are using any third party script file, you can copy its content to your single script file. It will save DNS look up time.

If you can not combine all scripts in one file, try to make it for one file for one domain script (e.g. make a one script file for all scripts referring from jQuery website). It reduces DNS lookup time.

Apply the same tips for css files.

2. Minify script and css files: You should minify your script and css files to reduce its size. Minification will remove spaces from script or css files and replace the long keywords with small characters. You can use this tool for minification.

3. Script reference: Use script references at the bottom of the page because async downloads halt when script reference is reached. Stylesheet and images can be download in async.

4. Async Scripts: Below code allows you to download script files asynchronously.


<script async src="slow.js"></script>

            

If clients browsers are old. This can be use for script and css files.


<script type="text/javascript">
    var link = document.createElement("link");
    link.type = "text/css"; link.rel = "stylesheet";
    link.href = "Styles/Site.min.css"; 
    document.getElementsByTagName("head")[0].appendChild(link)</script>

            

Content Delivery Network

Use the Content Delivery Network(CDN) for hosting images and script files. These files can be cached and reduce the load on server.

A content delivery network (CDN) is a bunch of web servers shared across multiple locations to deliver content more efficiently to users. Depending on the user's location and measure of network proximity server is selected for delivering content. It looks for server with the fewest network hops or the server with the quickest response time.

The users' location with respect to location has an impact on page load time. Deploying your content to geographically dispersed server or near to your most intended website audience. Watch this video to learn how to use CDN for asp.net application

Remove unused client scripts

Visual Studio by default adds many client scripts to your ASP.NET application. All of them may not be useful for your application. So before deploying to production you must remove unused or duplicate script files.

Optimization of Images

Below are some tips to optimize images

1. Reduce size by optimizing Images: You can download Image Optimizer from the Visual Studio gallery which is easy to use. Download Image Optimizer from asp.net website. It helps you to reduce your image size by 20-25%.

2. Image height and width: If you know the image height and width at design time you should set it for <img /> tag. Doing so space gets allocated before image download.

3. Image Sprites: Use Image Sprites to retrieve small images in a single request. It preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment. Download this nugget package which gives you API for automatically generating sprites and inline images.

AJAX Asynchronous

Use AJAX to retrieve components asynchronously that may not be needed immediately, such as the content of a collapsed panel, the content behind a tab, and so on.

Remove HTTP Modules

Remove HTTP modules that are not being used like Windows Authentication and disabled services like FTP, SMTP if you are not using them. It reduces the load on the server to process requests and responses.

Caching

Many developer say caching is the best and only solution to improve performance. However, you should first take care of all of the above solutions and then implement caching. This strategy will give you a significant boost to your application.

Caching allows you to store objects on a web server after first request and subsequent requests served through cache without much processing. In ASP.NET you can achieve caching in two ways.

1. Output Cache: Output cache allows you to store entire aspx page or user control's HTML to be stored in the web server's memory. This cache can be valid for a certain duration and can be made invalid depending on different attributes.


 <%@ OutputCache Duration="60" VaryByParam="None" VaryByCustom="browser" %>          
    
            

2. Cache Object: Using Cache object you can store any serializeable object in memory. You can use Insert, Remove methods on cache object. These cache objects can be made invalid on some dependecies.


Cache.Insert("uservalues", userFileData, new 
    System.Web.Caching.CacheDependency(Server.MapPath("~/users.xml")));
            

Dispose objects

The objects which you create should be removed from memory as soon as you are done with using that object. .NET framework has given Garbage Collector to manage memory however it has its own algorithms to reclaim memory. So it is always better to reclaim object's memory as soon as possible. You can release objects using Dispose and Finalize methods. For more on how to implement Dispose and Finalize.

Speak your mind
Please login to post your comment!


Blog Search





If you like my content please feel free to buy me coffee. Buy Me A Coffee