Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Code Optimization in ASP.NET

Code Optimization in ASP.NET

This article gives a simple checklist that can simply be run against any ASP .NET Web Page to optimize it.

Author Rank :
Page Views : 7664
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction

This article gives a simple checklist that can simply be run against any ASP .NET Web Page to optimize it. This is in no way a complete list, however it should work for most of the web pages. For a performance critical application you will surely need to go beyond this checklist and will require a more detailed plan.

Checklist for all pages

Here is the list of checks that you need to run, not necessarily in order:

  • Disable ViewState - Set "EnableViewState=false" for any control that does not need the view state. As a general rule if your page does not use postback, then it is usually safe to disable viewstate for the complete page itself.
  • Use Page.Ispostback is used in Page_Load - Make sure that all code in page_load is within "if( Page.Ispostback)" unless it specifically needs to be executed upon every Page Load.
  • Asynchronous calls for Web Services - If you are using Web Services in you page and they take long time to load, then preferably use Asynchronous calls to Web Services where ever applicable and make sure to wait for end of the calls before the page is fully loaded. But remember Asynchronous calls have their own overheads, so do not overdo it unless needed.
  • Use String Builder for large string operations - For any long string operations, use String Builder instead.
  • Specialized Exception Handling - DO not throw exceptions unless needed, since throwing an exception will give you a performance hit. Instead try managing them by using code like "if not system.dbnull �." Even you if you have to handle an exception then de-allocate any memory extensive object within "finally" block. Do not depend on Garbage Collector to do the job for you.

http://www.codeproject.com/images/minus.gifCollapse

//

 

// Try

 

//        'Create Db Connection and call a query

 

//        sqlConn = New SqlClient.SqlConnection(STR_CONN)

 

// Catch ex As Exception

 

//        'Throw any Error that occurred

 

//        Throw ex

 

// Finally

 

//        'Free Database connection objects

 

//        sqlConn = Nothing

 

//End Try

 

//

 

  • Leave Page Buffering on - Leave Page buffering On, unless specifically required so. Places where you might require to turn it on in case of very large pages so that user can view something while the complete page is loading.
  • Use Caching - Cache Data whenever possible especially data which you are sure won't change at all or will be reused multiple times in the application. Make sure to have consistent cache keys to avoid any bugs. For simple pages which do not change regularly you can also go for page Caching

http://www.codeproject.com/images/minus.gifCollapse

//

 

// <% @OutputCache Duration="60" VaryByParam="none" %>

 

//

 

Learn more about "VaryByParam" and "VaryByControl" for best results.

  • Use Script files - As a rule unless required do not insert JavaScript directly into any page, instead save them as script file ".js" and embed them. The benefit being that common code can be shared and also once a script file is loaded into browser cache, it is directly picked up from browser cache instead of downloading again.
  • Remove Unused Javascript - Run through all Javascript and make sure that all unused script is removed.
  • Remove Hidden HTML when using Tabstrip - In you are using a Tabstrip control and if the HTML size is too large and the page does frequent reloads, then turn Autopostback of Tabstrip on, put each Pageview inside a panel and turn visibility of all Panels except the current one to False. This will force the page to reload every time a tab is changed however the reload time will reduce heavily. Use your own jurisdiction to best use.

Additional Checklist for performance critical pages

  • Disable session when not using it - If your page does not use session then disable session specifically for that page.

http://www.codeproject.com/images/minus.gifCollapse

//

 

// <%@ Page EnableSessionState="false" %>

 

//

 

If the page only reads session but does not write anything in session, then make it read only.

http://www.codeproject.com/images/minus.gifCollapse

//

 

// '<%@ Page EnableSessionState="ReadOnly" %>

 

//

 

  • Use Option Strict On (VB .Net only) - Enabling Option Script restricts implicit type conversions, which helps avoid those annoying type conversion and also is a Performance helper by eliminating hidden type conversions. I agree it takes away some of you freedom, but believe me the advantages outweigh the freedom.
  • Use Threading - When downloading huge amounts of data use Threading to load Data in background. Be aware, however, that threading does carry overhead and must be used carefully. A thread with a short lifetime is inherently inefficient, and context switching takes a significant amount of execution time. You should use the minimum number of long-term threads, and switch between them as rarely as you can.
  • Use Chunky Functions - A chunky call is a function call that performs several tasks. you should try to design your application so that it doesn't rely on small, frequent calls that carry so much overhead.
  • Use Jagged Arrays - In case you are doing heavy use of Multi Dimensional Arrays, use Jagged Array ("Arrays of Arrays") Instead
  • Use "&" instead of "+" - You should use the concatenation operator (&) instead of the plus operator (+) to concatenate strings. They are equivalent only if both operands are of type String. When this is not the case, the + operator becomes late bound and must perform type checking and conversions.
  • Use Ajax - In performance critical application where there are frequent page loads, resort to Ajax.
  • Use the SqlDataReader class - The SqlDataReader class provides a means to read forward-only data stream retrieved from a SQL Server� database. If you only need to read data then SqlDataReader class offers higher performance than the DataSet class because SqlDataReader uses the Tabular Data Stream protocol to read data directly from a database connection
  • Choose appropriate Session State provider - In-process session state is the fastest solution. If you store only small data in session state, go for in-process provider. The out-of-process solutions is useful if you scale your application across multiple processors or multiple computers.
  • Use Stored Procedures - Stored procedures are pre-compiled and hence are much faster than a direct SQL statement call.
  • Use Web Services with care - Web Services depending on data volume can have monstrous memory requirements. Do not go for Web Services unless your Business Models demands it.
  • Paging in Database Side - When you needs to display large amount of Data to the user, go for a stored procedure based Data Paging technique instead of relying on the Data Grid/ Data List Paging functionality. Basically download only data for the current page.

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Amit Choudhary
Amit is a software developer by profession and blogger by choice. He's Practicing in C#, .Net framework, ASP.NET, Silverlight, Windows Phone, ADO.NET, Linq,  Xml, Web Services, JQuery, and Sql server. Amit is MindCracker MVP. Visit Amit's blog - www.cshandler.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.