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.

devx-admin

devx-admin

Share the Post:
Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years,

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW)

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the