Improving ASP.NET Application Performance and Scalability

Improving ASP.NET Application Performance and Scalability

any factors influence application performance, but in essence, the most important is to be aware of how to optimize your applications so they consume the least amount of memory and require the least amount of processing to produce the desired output in a managed environment.

This article discusses some best practices that you can follow during an application’s development life cycle to help ensure that your application is both scalable and achieves high performance. You don’t have to use special tools to achieve this, just write structured, readable code, paying particular attention to techniques that are instrumental for improving, optimizing and boosting the performance of .NET applications.

Reducing Page Load Time
Avoid excessively large images, redundant tags, and nested tables to facilitate faster page loads. Always avoid unnecessary roundtrips to the web server. Use client side scripts to dramatically reduce server roundtrips, thereby boosting the perceived, if not the actual application performance. Take advantage of the Page.IsPostback property to avoid unnecessary server processing on a roundtrip, reducing network traffic. I suggest you leave page buffering on (it is turned on by default) for a page unless you have a specific reason to turn it off.

You can pre-compile web pages in your application to reduce the working set size and boost application performance. Set AutoEventWireup attribute to false in the section of the server’s Machine.config file to improve performance further, e.g.:


The AutoEventWireup attribute accepts a Boolean value that indicates whether the ASP.NET pages events are auto-wired. If the AutoEventWireup is set to false, the runtime does not have to look for each of the page event handlers. This MSDN article about the AutoEventWireup Event concludes with, “When you explicitly set AutoEventWireup to true, Visual Studio .NET or Visual Studio 2005, by default, generates code to bind events to their event-handler methods. At the same time, the ASP.NET page framework automatically calls the event-handler methods based on their predefined names. This can lead to the same event-handler method being called two times when the page runs.” The article therefore recommends that you always set AutoEventWireup to false while working in Visual Studio .NET.

Efficient ASP.NET State Management Practices
ViewState is great for storing control state but can degrade performance?especially on web sites with large page sizes. If you’ve ever looked at a page that contains a large DataSet, you know the amount of data stored in ViewState can be overwhelming. Every byte added to a web page by enabling its ViewState causes two bytes of network traffic, one in each direction. Evaluate whether each web page you write requires ViewState and avoid it when possible to speed up the page-load cycle in your applications. You should typically use ViewState only for controls that need to persist state. You can turn ViewState on or off at four levels: machine, application, page, and control. Limiting the size of the ViewState and eliminating its unnecessary usage would boost the application performance to a large extent due to the reduced size of the rendered pages and hence the network traffic. It should be noted that each byte of the view state causes two bytes of network traffic for each request, one from the server to the client and the other from the client to the server. For more information on ViewState and how to turn it off at control, page, application, or machine levels, see this article .

You can remove the runat=”server” form tag completely to reduce page size by 20 bytes. If you don’t remove this tag, the page itself passes on about 20 bytes of information to ViewState?even when the page’s ViewState property is set to false.

Caching is one of the best strategies for storing relatively static application data. Caching reads data from memory to avoid repeatedly retrieving data from a database, file, or any other repository, and it can provide huge application performance gains. Use Page Output, Page Fragment or Data Caching directives depending on your requirements. Cache application-wide data that multiple users of the application need to share and access, but avoid storing user-specific data in the cache.

Use Session State only for storing a single user’s session data. Avoid storing too many objects in the Session and turn Session State off for pages that do not need to access session data. You can turn Session State on or off at the same four levels as ViewState: machine, application, page, and control.

Note that there are three Session State storage modes. The right type of storage mode to choose depends on factors such as, speed, security, scalability, and reliability. Even though the InProc mode of Session State storage is the fastest, it is not at all well suited to a production environment and not scalable for large sites. The OutProc storage mode is well-suited for web sites with heavy traffic, while the SqlServer mode is great for securing session data. No matter which mode you choose though, Session State has one major disadvantage: the resource will be increasingly strained as you scale up. There are always tradeoffs. The best mode for security, scalability, and reliability is not always the best mode for performance, and vice versa.

Tips for Efficient Memory and Resource Management
I’ve listed a few tips in this section that can help you avoid problems. I don’t have room to explain each tip in-depth here; instead, I’ve provided a basic description and added links where appropriate so you can explore further on your own.

Try never to refer to a short-lived object from a long lived one to avoid promoting short-lived objects to higher generations. Note that the .NET Garbage Collector (GC) works more frequently against lower generations than against higher ones. An in-depth discussion of the .NET GC is beyond the scope of this article, but this two-part MSDN article on garbage collection (Part 1, Part 2) provides more background

Avoid any code that can promote an object to a higher generation unnecessarily as shown in the code snippet below:

   class Employee   {    EmployeeRegister empRegister;     void Create (int empCode, int deptCode, double basic)      {       EmployeeRegister empRegister = new EmployeeRegister();       empRegister.Create(empCode, deptCode, basic);       this.empRegister = empRegister;      }   }   

Use Dispose and Finalize appropriately to handle unmanaged resources (for more information, see my article When and How to Use Dispose and Finalize in C#. In fact, you should avoid implementing the Finalize method as much as possible.

Set any objects no longer required to null prior to making any long-running calls. Developers often set locals to null after they’re done using them, but in .NET, that’s not required, as the GC can safely determine when objects are no longer needed or are not reachable, thus making them eligible for garbage collection. However, if you use machine resources such as files, database connections, or unmanaged objects, remember to release them in a finally block?never in a catch block.

Author’s Note: In C#, it’s best to wrap resource-handling code within a using block to ensure that the resources are disposed of properly when they’re no longer needed. When you use the using statement, the .NET framework implicitly creates finally blocks for those objects that implement IDisposable.

Acquire resources and locks late and dispose of them as soon as possible. Ensure that you free or dispose unneeded resources and locks properly.?In fact, I recommend that you avoid locking and synchronization altogether unless it’s absolutely necessary. ?Do not lock on the this object?it’s better to lock on a private object. ?If you lock on the current object instance (this), all the members of the object are also locked irrespective of whether a lock is required on them. Do not lock on object types, only on objects themselves.

Efficient Exception Management
Exceptions are errors that occur at run time. Exceptions are generally well understood but quite often used improperly. An understanding of proper exception handling is one of the more important aspects of efficient programming.

Handle only those exceptions that you know how to handle and avoid handling those that you don’t know how to handle. As Eric Gunnerson, a former member of Microsoft’s C# team, says in his blog, “the essence of exception handling is to be able to respond to a specific exception in a specific situation.”

When possible, reduce the number of try…catch blocks in your code; exceptions take longer to be processed and can reduce application performance drastically. Do not use exceptions to control an application’s logic flow. Use proper validation techniques instead of exceptions to avoid throwing unnecessary exceptions.

Efficient Data Access Strategies
Prefer DataReaders to DataSets. DataReaders are much faster than DataSets for simple sequential data access. Use a DataReader for fast data-rendering, but not to pass data between layers of the applications or through different application domains?unlike DataSets which can work in disconnected mode and can be cached, DataReaders always require an open connection. When you do have to use a DataSet, you can often set its EnableConstraints property to false and use the BeginLoadData and EndLoadData methods for faster data rendering. If you are using transactions keep them short to minimize the lock durations and to improve data concurrency.

Open database connections as late as possible and close them immediately when done. Effective use of connection pooling can increase application performance by reducing the number of roundtrips to the server. Note that each database request in a distributed environment creates network traffic that can cause performance bottlenecks and degrade the application’s performance. Try to minimize the number of database connections in the application. Never hold a connection open, because that decreases the number of available connections in the connection pool and hence degrades performance if the demand for connections exceeds the pool count. See this article for more information on connection pooling.

Efficient Coding Practices
Avoid late binding whenever possible. Late-binding adds flexibility but is always slow compared to early binding. Note that using virtual methods in your code requires late binding, because virtual methods must be mapped. Any class that contains a virtual method has its own virtual table. The virtual table in turn contains entries that correspond to the virtual methods that the class contains. Note that the virtual method is class specific; there can be only one virtual table per class regardless of how many virtual methods the class contains. The runtime uses the virtual table to map a virtual method to the object on which it is called. Hence there’s additional overhead involved (more resource usage?both processor and memory) in binding a virtual method to the object on which it is called to satisfy a virtual method call.

You should seal final classes (those that cannot be inherited) for performance gains.

Avoid recursive method calls and try to replace them with loops instead. Inline frequently called code inside loops. Avoid calling methods or properties repetitively inside a loop. Especially, avoid situations that will require boxing and unboxing of value types, because that carries performance overhead?use generics instead when possible, building strongly typed collections to avoid boxing and unboxing issues. This link provides more information.

Avoid inefficient string operations (see this article for more information) and use collections (if needed) efficiently.

Choosing between Server.Transfer and Response.Redirect
Use the Server.Transfer method to redirect between pages in the same application; Server.Transfer avoids an unnecessary client-side redirection. However, you cannot always just replace Response.Redirect calls with Server.Transfer. If you need authentication and authorization checks during redirection, use Response.Redirect instead. The two mechanisms are not equivalent. When you use Response.Redirect, make sure you use the overloaded method that accepts a Boolean second parameter, and pass a value of false to ensure an internal exception is not raised. Also note that you can only use Server.Transfer to transfer control to pages within the same application. To transfer to pages in other applications, you must use Response.Redirect.

Use Best Practices?and Common Sense
Even though there is no specific methodology that can fit in each and every environment, using best practices such as those discussed in this article?can yield better application performance. You should plan and set some well-defined performance objectives, create performance test plans, performance checklists, and perform periodic tests based on the test plans. Keep these performance factors in mind when designing applications. This process should be iterative and repeated until we meet the predefined performance goals.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist