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-part 2
Posted By Sarin on Mar 22, 2012     RSS Feeds     Latest Hinduism news
2589 Views

optimize

      1)    Use StringBuilder for Complex String Manipulation
        When a string is modified, the run time will create a new string and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do it, but when a string is being modified repeatedly it begins to be a burden on performance: all of those allocations eventually get expensive. Here's a simple example of a program that appends to a string 50,000 times, followed by one that uses a StringBuilder object to modify the string in place.  
  
        string str = "";
            DateTime dStartTime = DateTime.Now;
            Response.Write(("<br>String Concatenation start time:" + dStartTime.ToString()));
            int i;
  
            for (i = 0; i < 20000; i++)
             {
                str += i.ToString() + "<br>";
            }
            DateTime dEndTime = DateTime.Now;
            Response.Write(("<br>String Concatenation End time:" + dEndTime.ToString()));
  
            StringBuilder sb = new StringBuilder();
            DateTime dStartTime1 = DateTime.Now;
            Response.Write(("<br>StringBuilder Start time:" + dStartTime1.ToString()));
            int i1;
  
            for (i1 = 0; i1 < 20000; i1++)
             {
                sb.Append(i1 + "<br>");
            }
            DateTime dEndTime1 = DateTime.Now;
            Response.Write(("<br>StringBuilder End time:" + dEndTime1.ToString()));  
    
Check the output below to see the differences between the two


String Concatenation took 16 seconds to execute whereas stringbuilder did it in less than one second.
  
  2)    Disabling AutoEventWireup
         Also setting the AutoEventWireup attribute to false in the Machine.config file means that the page will not match method names to events and hook them up (for example, Page_Load). If page developers want to use these events, they   will need to override the methods in the base class (for example, they will need to override Page.OnLoad for the page load event instead of using a Page_Load method). If you disable AutoEventWireup, your pages will get a slight   performance boost by leaving the event wiring to the page author instead of performing it automatically.  
  
You can also disable AutoEventWireup  on Page level as shown below
       <% @ Page Language="C#" AutoEventWireup="true" %>
   
You can also disable AutoEventWireup  on Application level as shown below
       <pages  AutoEventWireup="false" />
    
This is a major performance gain since we can work without these auto events in most of the pages in our application  
  
  3)     Precompiling pages  
         By precompiled pages, users do not have to experience the batch compile of your ASP.NET files;  
Precompiling an ASP.NET Web site provides faster initial response time for users because pages do not have to be compiled the first time they are requested. This is particularly useful for large Web sites that are updated frequently. In order to achieve Precompiling, we can use ASP.NET Compilation Tool (Aspnet_compiler.exe).

  4)    Process Model Optimization
        ASP.NET allows you to define many process level properties. By default all these properties are set to auto configuration. This means that ASP.NET automatically configures maxWorkerThreads, maxIoThreads, minFreeThreads, minLocalRequestFreeThreads and maxConnection to achieve optimal performance. You can tailor these by specifying your own value to achieve better performance. Some of the major settings are:  
  
  • maxWorkerThreads. The default value is 20 per process and it determines the maximum number for request that ASP.NET can process in a given second. For application that are not CPU intensive and most of time wait on database request or any external processing this can increased to get better performance.
  • maxIOThreads. The default value is 20 per process and it determines the maximum number for I/O request that ASP.NET can process in a given second. If you have enough I/O resources you can increase this value for better results.
  • memoryLimit: The default is 60%. This is the max memory ASP.NET can use until worker process is refreshed. If you have a dedicated web server with no other services running you can increase this value for better results.
  • connectionManagement: This is a property of System.Net configuration and specifies the maximum parallel connections that can be established to a server. If your web application extensively connects to other server you can increase this value.
          5)    Enable Buffering
            Make sure that buffering is enabled unless you have a specific need to turn it off. By default its enabled. ASP.Net sends response to IIS in a 31 KB buffer which then passes that to the client. When buffering is disabled ASP.NET only sends few characters to IIS thus not utilizing this buffer and increasing the trips between IIS and the worker process. To enable it you can change the web.config or enable it on each page through @page directive
      
    You can Enable Buffering on Page level as shown below
           <% @ Page Buffer="true"%>
       
    You can also Enable Buffering on Application level as shown below
           
          <pages  buffer="true">
        
      6)    Use Caching Techniques
        
        Caching in ASP.NET dramatically help in boosting application performance by reducing the load on the underlying server and serving cached content that doesn’t need to be recreated on each request. ASP.NET provides three types of caching:  
      
  • Output Cache which stores dynamic pages and user controls. One each request code is not executed if a cached version of page or control is available
          
  • Fragment caching : Same as Output caching, only difference being the functionality of caching only the fragments of the page instead of whole page
  • Data Cache which allows application to save application objects, Dataset etc in server memory so they are not recreated on each request.
          7)    Kernel Cache
            Use Kernel Cache if you are using IIS 6 or above. When Output cache is used in ASP.NET the request still goes to ASP.NET that itself returns the cached content. However if Kernel Cache is enabled and the request is output cached by ASP.NET, IIS receives the cached content. If a request comes for that data again IIS will serve the cached content and end the response. This can save valuable CPU cycles as it minimizes work performed by ASP.NET.  
      8)    Avoid using Response.Redirect
            Instead of using Response.Redirect, use Server.Transfer where ever you can. Response.Redirect sends response to the client which then sends a new request to the server. Server.Transfer however performs the redirect directly on the server and hence, reduces one extra roundtrip onto the server. Use Response.Redirect only when you want authentication and authorization to be performed on redirects or you want URL on client browser to be changed  
    In Server.Transfer, by using HttpContext we can access the source page’s items collection in target page.  The drawback of using this method is that the browser does not know that a different page was returned to it.  It displays the first page’s URL in the browser’s address bar.  This can confuse the user and cause problems if the user tries to bookmark the page.  

      9)    Save or Compress ViewState
        
        In case where ViewState in mandatory and the ViewState contains enough data that can cause Network congestion or increase download response time for the user try saving or compressing the ViewState. The Page class provide two very useful methods LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium(object ViewState). You can override these methods to either compress the ViewState or even prevent it from going to the client by saving it in some persistent medium on the server.  
      10)    Use HTTP Compression
            If your page size is large enough to cause noticeable lag between subsequent request and response you can use HTTP compression. HTTP compression is a feature of IIS and what it means is that you can compress data sent to the client using compression techniques like GZIP and Deflate. On the other side the browser decompresses the data and shows the response to the client. Most of the modern browsers are capable of handling compressed data. You will certainly get a huge performance boost if your page size is large.  
      11)    Optimize Data Paging / Sorting
            Whenever using data grid to show data with paging enabled and let say, if your query returned 5000 records and you are only showing 100 records per page then the remaining 4900 record will be discarded and the same will happen whenever you will change the page or apply sorting. The additional 4900 rows will definitely take up memory and if your database is located on a different server which is most commonly the case you will also be transferring unnecessary data over the network. Make sure you are only returning the required results to the ASP.NET application by filtering out the data in your database query and apply custom paging.  
      12)    Use Connection Pooling
            Creating a connection to a database is a resource intensive process and takes time. Connection pooling allows you to reuse these connections saving time and resources. When a new connection is requested the connection pool managers first searches in the connection pool and if doesn’t finds one, it creates a new one. There are various things that need to be done to use connection pooling effectively:  
      
  • Avoid Connection Leakage. This means that you opened a connection but didn’t close it. If you don’t close the connection the connection pool manager will never put it in the pool for later reuse until the GC is called.
  • Use the same connection string. Connection pool manager searches for similar connection in the pool by the connection string.
  • Use SQL Servers and .NET CLR Data performance counters to monitor pooling.
  • Open connections as late as possible and close them as early as possible
  • Don’t share same connection between multiple function calls. Instead open a new connection and close it in each function.
  • Close transactions prior to closing the connection.
  • Keep at least one connection open to maintain the connection pool.
          
      13)    Trim Page Sizes
            Reduce page size by removing any unnecessary space and tab characters from the page. As a result network traffic will be reduced.
    Moreover, it will also reduce the compiler task of handling such spacing issues.
      
      14)     Use a CDN
            Not a performance tip exclusive to ASP.NET but an important step in speeding up a site is to use a Content Delivery Network (CDN). CDN’s minimize the latency site visitors experience when they request a larger file from a data center that is located geographically far away. CDN’s cache files at numerous edge locations around the world to minimize latency. One of the most common uses of CDN is to load Jquery files from various CDN available on the net

      15)    Locking and Shared Resources
            Acquire shared resources late and release them as early as possible.  Avoid locking unless absolutely necessary.  Do not set lock on the “this;” it is better to use a private object to lock on as follows:
      
    public Class Test
      {
        private static readonly objLock=new Object();
        public static Test Singleton
         {
          lock(ObjLock)
           {
            return new test();
              }
    }
      
      16)     Enable Option Strict and Option Explicit for your pages.
            This tip is only applicable to Vb.net developers. You should never trust .net or any compiler to perform conversions for you.  That’s just shady programming, and not only produces low quality code but also add additional burden on the compiler to perform the conversion and hence increase response time.    
      
      17)     Use 'using' statment to dispose resources
            The using statement defines a scope at the end of which an object will be disposed even if an exception is thrown, please note that the object that you are trying to dispose should implement 'System.IDisposable'.The following code demonstrates the disposal of sqlconnection string.  

     using (SqlConnection cn = new SqlConnection(connectionString))

      18)     Avoid Recursive Functions / Nested Loops  
        Sometimes due to wrong input or some error in input values, recursive function can result in a stack overflow and may even crash your web server. Problem associated with nested loops are that many times, code inside nested loops unnecessarily gets executed. Hence increasing the throughput time. Also, nested loops add complexity to the programs and if the nested loop is not coded properly to come out of the loop, it will result in a stack overflow and may even crash your web server
          19)    Avoid Server Side validation
        Handle most of the input validation using client side JavaScript code since it removes the burden from the server. However there is a scenario where this validation can be bypassed by disabling javascript through browser. For such cases, check if the page is valid using Page.IsValid (Which checks if the input passed the given set of rules). If page is not valid then call server side validation to handles all the input validations. Not defining server side validation can cause HTML code injection and sql injection and hackers can even crash your website.
        
      20)    Optimize Stored Procedures
            If your website makes lot of stored procedures call to the database, then optimizing each stored procedures will give a very vital performance gain.
          When you create stored procedures, below are some of tips to be kept in mind:  
      
  •  Use Set NOCOUNT ON in stored procedures, if you turn on the NOCOUNT option, stored procedures will not return the row-count information to the client, and this will prevent SQL Server from sending the DONE_IN_PROC message for each statement in the stored procedure.
  •  Do not use the sp_ prefix for custom stored procedures, Microsoft does not recommend to use the prefix "sp_" in the user-created stored procedure name, because SQL Server always looks for a stored procedure beginning with "sp_" in the master database
          

  • 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