Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment


Locations of visitors to this page


Latest Articles


Move to top
Performance and optimization tips(ASP.Net)
Posted By Sarin on Mar 18, 2012     RSS Feeds     Latest Hinduism news
3303 Views

webservice

  
Some of the performance tips very useful during development, production and testing
  
  1)     Set debug="false" during deployment of your application
  NEVER deploy your web application to production with debug set to true.  Below are some of the performance degradations if debug is set to true:
    
  • The compilation of ASP.NET pages takes longer (since some batch optimizations are disabled)  
  • Code can execute slower (since some additional debug paths are enabled)  
  • Much more memory is used within the application at runtime  
  • Scripts and images downloaded from the WebResources.axd handler are not cached
            
       <compilation  debug="false"  targetFramework="4.0" />
      2)    Set trust level to medium.
            Medium trust level gives you the optimal performance. However, there are quite a few things you cannot do in ASP.Net while using Medium Trust. In most cases, you can work around this, but it is better to know before you you write the code than to know when a visitor sends you an error message  
    Note: By far, the most frequent case of medium trust issues is external HttpRequests. Under medium trust it is not possible to make an external Http Request without changes to your local policy or via a proxy <https://weblogs.asp.net/hosterposter/archive/2006/03/22/440886.aspx>.  
      
         <trust  level = "Medium" />
        
      3)    Build Poject in Release mode before Deployment
            If you build/rebuild your application in debug mode, many things happens in the background. First of all, it creates an additional PDB File under your BIN directory which holds all the Debug information. Secondly, the Time required for execution is very high since compiler has to take additional care of breakpoints and also its execution.  
    So, selecting Release Mode during deployment will greatly improve the performance of the application  
      
      4)    Turn off Tracing unless until required.  
             Tracing is one of the wonderful features which enable us to track the application's trace and flow of control. However, again it is useful only for developers and hence, before going to production, you should set this to "false" unless you need to monitor the trace logging.
      You can disable tracing in the Machine.config and Web.config using the syntax below.
      You can turn off tracing as follows: -
      
    <configuration>
       <system.web>
          <trace  enabled="false"  pageOutput="false" />
       </system.web>
           </configuration>
      
      
      
      
      5)     Disable session state if not used.
            Efficient state management helps to boost the performance and scalability of application. It is not advisable to keep large objects in a session variable and it is optimal to disable session state whenever it is not required.  ASP.NET does this session state management automatically. However, in case you don’t require Sessions, disabling it will help in   improving the performance. Performance gain is significant in case of simple websites with static contents. However, most applications can be written without the use of session variables
      
    We can turn session state off either at the Page level or at the application level using the  web.config file.
      
              You can set sessionstate to false at application level as shown below:
            <sessionState  mode="Off" />
      
              You can also disable sessionstate to false on Page level as shown below
          <% @ Page EnableSessionState="false" %> 
        
      6)     Disable ViewState
            View state is very important concept and essential requirement for many web apps but in many cases, your webpage may not need view state. In such cases, storing viewstate leads to unnecessary page requests. Major use of viewstate is in storing state of databound controls (Repeater, DataList, DataView, and DataGrid) which are loaded on the initial page load. During post back requests, Instead of rebinding the controls, data stored in the ViewState is used. So, if your webpage is not using this data bound controls, then there is no need of using viewstate
      
    ViewState is also used by server controls so that they can retain their state after postback. You can also save your objects that are marked Serializable in the ViewState. ASP.NET serializes all objects and controls in the ViewState and transmits them in a hidden field to the browser. If not managed properly ViewState can increase page size and therefore increase network traffic. Also precious CPU cycles are used for Serialization and De-Serialization of ViewState objects
      
    In short, Disable view state in any of the following scenarios:
    1)  A readonly page where there is no user input.
    2) A page that does not postback to the server
    3) A page which requires rebuilding server controls on each post back without checking the post back data.
    4) You controls are not bound to a data source or they don’t handle server events like OnClick, OnSelectedIndexChanged etc or their properties are set on each postback
      
    It is best practice to turn ViewState off at the application level and then enable it as required at the page or even control level.

    For each page of your website, Check if there is a need of storing viewstate. If not, then simply set EnableViewState =false as shown below. In fact, you should start development of each page by setting EnableViewState =false.
      
    <% @ Page Language="C#" EnableViewState="false" %>

    You also have the option of disabling view state for only some controls of your webpage, you can do it as shown below:
           <asp:DropDownList EnableViewState="false" />
        
    You can also disable view state of your whole web apps by setting viewstate to false in web.config file.
    <pages  enableViewState="false" />
      
    Finally, keep in mind that controls like the TextBox do NOT need view state enabled to maintain their state.
      

      7)     Avoid frequent round trips to the Database.
             Calls made to Database can be quite expensive in terms of response time as well as resources and bandwidth. So, such database calls should be avoided by using Batch Processing.  
      Also do performance tuning of your sql query and stored procedures. Use Data Adapter wherever applicable since it automatically handles opening and closing of Connection and doesn’t require user to explicitly open the connection.  
      A number of connections opened and not closed can cause great performance degradation depending upon the active users. Also, it increases the burden on garbage collector to dereference such opened connection. As a standard solution, use your Try..Catch.. Block, followed by the finally method to close Open connections
      8)    Declare your Custom Server Controls
             Instead of registering your user controls on applicable pages of your website, declare your custom user controls in the web.config file and then used it in the pages (which uses this user control) of your website. This allows you to skip the step of adding a Register directive at the top of any page which uses the controls. Additionally, it adds consistency across pages since the TagPrefix is always the same.  
      9)     Know when to use configSource attribute
            The configSource attribute lets you move entire sections of your web.config to another file.  
      
         <connectionStrings  configSource="connectionStrings.config" />
      
        There are two main reasons for using this feature:
    It lets you isolate locally changeable sections which can make source code management easier. For example, if you change connection strings frequently, then move our connection strings to a separate config file.
    It just makes the web.config easier to read. For huge applications, web.config file is usually very large. Using configSource allows you to break such config files into many smaller more readable chunks.
      10)     Use ASHX files for HttpHandlers
            If you are using HttpHandlers then Instead of configuring a path and type in the HttpHandlers section of web.config file, simply add an ASHX file and use HttpHandlers there.  
    There are still times when you cannot use ASHX file and you need to use the web.config method (a single handler for multiple paths, a different handler by verb, etc), but in most cases such as serving RSS or handling images you can very easily use the ASHX file.  
      
      11)    Throw Fewer Exceptions
            Throwing exceptions can be very expensive, so make sure that you don't throw it unnecessarily. Use Perfmon to see how many exceptions your application is throwing and whether you can avoid most frequently occurring exceptions.  
    Writing code with fewer exceptions can result in a decent performance improvement. This has nothing to do with try/catch blocks. In fact, your application faces the burden when the actual exception is thrown. You can use as many try/catch blocks as you want. But use exceptions intelligently so as to gain performance. Beside user defined exceptions, dot net compiler throws system defined exceptions at runtime. So, use Perfmon to check the source of the exceptions and write code to avoid it.
    Here's a simple example on how expensive exceptions can be: we'll simply run through a for loop, generating thousands or exceptions and then terminating. Then we will run the same example by commenting out the throw statement to see the difference in speed
      
           dStartTime = DateTime.Now;
                Response.Write(("<br>With Exception Start time:" + dStartTime.ToString()));
                int j = 0;
                for (i = 0; i < 1000; i++)
                 {
                    try
                     {
                        j = i;
                        throw new System.Exception();
                    }
                    catch  
                }
                dEndTime = DateTime.Now;
                Response.Write(("<br>With Exception  End time:" + dEndTime.ToString()));
      
      

        With Exception example took around 27 seconds to execute Without Exception example executed immediately within a second
      
      12)    use Value Type unless required otherwise
            For example, Use simple structure when you don't do a lot of boxing and unboxing and you don’t need OOPS concept for your requirement. Here's a simple example to demonstrate the speed difference:
           public struct foo
             {
                public foo(double arg)  this.y = arg;
                public double y;
            }
            public class bar
             {
                public bar(double arg)  this.y = arg;
                public double y;
            }
      
               for (i = 0; i < 50000000; i++)
                 {
                    foo test = new foo(3.14);
                }
                for (i = 0; i < 50000000; i++)
                 {
                    bar test2 = new bar(3.14);
                }
        
    When you run this example, you'll see that the struct loop executes faster than class loops. However, don’t use Value Types when you treat them like objects. This adds extra boxing and unboxing overhead to your program, and can end up costing you more than it would if you had stuck with objects! To see this in action, modify the code above to use an array or hashtables of foos and bars. You'll find that the performance is more or less equal.
    ValueTypes are far less flexible than Objects, and end up hurting performance if used incorrectly. You need to be very careful about when and how you use them.  
        
      13)    Use AddRange to Add Groups
            Use AddRange to add a whole collection, rather than adding each item in the collection iteratively. Almost all windows controls and collections have both Add and AddRange methods, and each is optimized for a different purpose. Add is useful for adding a single item, whereas AddRange has some extra overhead but wins out when adding multiple items. Here are just a few of the classes that support Add and AddRange:  
      
  • StringCollection, TraceCollection, etc.
      
  • HttpWebRequest
  • UserControl
  • ColumnHeader
              14)    Use For Loops for String Iteration-version 1
            In C#, the foreach keyword allows you to walk across items in a list, string, etc. and perform operations on each item. The tradeoff for this generalization is speed, and if you rely heavily on string iteration you should use a For loop instead. Since strings are simple character arrays, they can be walked using much less overhead than other structures. The JIT is smart enough (in many cases) to optimize away bounds-checking and other things inside a For loop, but is prohibited from doing this on foreach walks.  
    Here's a simple test method to demonstrate the difference in speed. Try running it, then removing the For loop and uncommenting the foreach statement

       public static void Main(string[] args)  {
      string s = "monkeys!";
      int dummy = 0;
      
      System.Text.StringBuilder sb = new System.Text.StringBuilder(s);
      for(int i = 0; i < 1000000; i++)
        sb.Append(s);
         s = sb.ToString();
      //foreach (char c in s) dummy++;
      for (int i = 0; i < 1000000; i++)
        dummy++;
      return;    
      }
    }
        
    Tradeoffs
      Foreach  is far more readable, and in some cases, it will be as fast as a For loop
        
      15)    Pick Data Reader Over Data Set When You Can
            Use a data reader whenever when you don't need to Process the data again somewhere else. This allows a fast read of the data, which can be cached if the user desires. A reader is simply a stateless stream that allows you to read data as it arrives, and then drop it without storing it to a dataset for more navigation. The stream approach is faster and has less overhead, since you can start using data immediately. DataReader is the most efficient means of data retrieval as they are read and forward only. DataSet are disconnected and in-memory therefore uses valuable server resources. Only use them when you need the same data more then once or want to do some processing on the data.
      16)     Use Ajax For partial page update
        Use either Microsoft Ajax toolkit controls or XMLHTTPRequest methods for partial page update of your page whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed.  
          17)    Keep IO Buffer Size Between 4KB and 8KB
      For nearly every application, a buffer between 4KB and 8KB will give you the maximum performance. For very specific   instances, you may be able to get an improvement from a larger buffer (loading large images of a predictable size,   for example), but in 99.99% of cases it will only waste memory. All buffers derived from Buffered Stream allow you to  set the size to anything you want, but in most cases 4 and 8 will give you the best performance
        
          18)    Optimize Assignments
      Use exp += val instead of exp = exp + val. Since exp can be arbitrarily complex, this can result in lots of unnecessary work. This forces the JIT to evaluate both copies of exp, and many times this is not needed. The first   statement can be optimized far well than the second, since the JIT can avoid evaluating the exp twice. 
            
      19)    Avoid DataBinder.Eval Calls
        Avoid calling DataBinder.Eval multiple times for example in case of grids, repeaters etc. Instead use Container.DataBind. DataBinder.Eval uses reflection to evaluate the arguments and therefore can decrease performance if called numerous times.  
      
          20)    Avoid Using Page.DataBind
            Never call Page.DataBind until you really need to do so. Instead if you want to bind a specific control, bind only that control. Calling Page.DataBind will call DataBind for all the controls that support binding.  
  • Note: Images used on this website are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

    Share this to your friends. One of your friend is waiting for your share.
    Related Articles
    Performance and optimization tips-part 2
    Performance and optimization tips(ASP.Net)
    Why I am proud to be an indian
    Working with canvas in silverlight

    Post Comment