#16
  1. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Variable Value Trimming


    Variable Value Trimming

    Be consistent when trimming values. Trim numeric values to the desired length before putting them in state. This will eliminate errors in processing caused by inconsistencies in trimming schemes. For example, a value such as 9.997 used repeatedly as a multiplier would accumulate a different result than the trimmed value 9.9. Trim unneeded leading and trailing spaces from strings by using LTrim, RTrim, or Trim, to eliminate the possibility of a space causing a processing error or a display misalignment.
  2. #17
  3. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Scripting for Performance


    Object and Variable Initialization

    The following information will help you to initialize and set dimensions for objects and variables, in order to achieve faster execution and efficient use of server resources. Unless stated otherwise, VBScript is assumed.


    Scoping Variables

    Using Page Scope for Best Performance


    Local variables reside within functions and subroutines. Give page scope (also called local scope) to variables unless you have a compelling reason to use a broader scope. For example, you might want to assign session scope to a variable that is used in more than one script in a user session. Local variables are compiled into table entries. At run time, references to local variables are resolved with fast-executing table lookups, giving local variables faster performance than global variables.


    Using Global Variables Sparingly and Efficiently


    Global variables are resolved at run time, and execute much more slowly than local variables. An undeclared global variable is the slowest, requiring a search of the entire variable list the first time it is used. When you need to give global scope to variables, declare them using the Dim statement before using them. This saves valuable time on first use by eliminating a search of the entire variable list.


    Avoiding the Use of Public Variables


    Do not use variables defined as Public. The Public keyword is under review to determine future use. Use Dim instead.


    Using Application Scope for Objects

    Information stored in variables with application-wide scope is in memory and is cached for access by any page in the application. Give application scope to variables used often within an application, if the values do not change frequently.


    Whatever the potential benefits, use caution in deciding whether or not to give application scope to an object. It can potentially affect performance and decrease reliability (your application could stop responding). To get the best performance using objects with application scope, set threading at BOTH.



    Avoiding the Use of Server Variables

    It is a best practice to avoid using server variables if your application does not need them. Whenever your ASP application accesses a server variable, your Web site makes a request that retrieves the server's entire variable collection—not just the variable to be used. This causes a performance hit the first time a server variable is used. You can enforce this restriction by setting the ENABLESESSIONSTATE directive to FALSE.

    Using the ENABLESESSIONSTATE directive (set in Internet Services Manager) for your site enables the detailed tracking of user requests.

    In order to save those resources that IIS uses to process scripts for pages not using session state information, set the ENABLESESSIONSTATE directive to FALSE for those pages:

    <%@ ENABLESESSIONSTATE=False %>


    Declaring Objects with the <OBJECT> Tag

    For objects that may or may not be used in an application, it's often most efficient to declare the objects without creating them.
    Last edited by bslintx; May 6th, 2005 at 02:39 AM.
  4. #18
  5. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    When Not to Use ASP


    Do not use scripts in ASP pages in order to perform tasks that are readily accomplished by browser scripts, since ASP consumes server resources. By scripting the browser to perform tasks such as data validation, calculations, and selection of simple conditional output, you can save server resources for those tasks actually requiring ASP. For example, you could use a client-side script in order to validate the input data and to calculate monthly payments for a user who enters a loan amount and specifies the length of the repayment cycle.

    To make the most efficient use of your server resources, use the .asp file name extension for pages that contain scripts or that are likely to need scripting in the future. Use the .htm extension for pages that will contain just HTML statements as well as scripts interpreted by the browser.
  6. #19
  7. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Using the Dictionary Object for Lookup


    The VBScript Dictionary object enables fast lookup of arbitrary key/data pairs. Because the Dictionary object gives you access to array items by key, it is fast for finding items that are not in contiguous memory, since you are specifying a key, rather than knowing where in the array the item is located.

    Use the Dictionary object when you have set a high priority on fast searches of nonlinear data.
  8. #20
  9. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Timing Out Connection Requests


    Busy data servers cause slowdowns in ASP database applications that request database connections. Use the ConnectionTimeout property of the Connection object. This limits the time your application has to wait in order for a connection request to complete.
  10. #21
  11. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Browser Connections and ASP


    Browser users often request an ASP page, then move on before the requested page has finished processing. Use the Response.IsClientConnected property to determine the connection status of the target browser. If the target browser is no longer connected, cut off ASP page processing to avoid wasting server resources.

    If the user gets impatient, he or she may abandon your ASP page before you even start executing their request. If he clicks Refresh or moves to a different page on your server, you will have a new request sitting at the end of the ASP request queue and a disconnected request sitting in the middle of the queue. Often this happens when your server is under high load (so it has a long request queue, with correspondingly high response times) and this only makes the situation worse. There's no point executing an ASP page (especially a slow, heavyweight ASP page) if the user is no longer connected. You can check for this condition by using the Response.IsClientConnected property. If it returns False, you should call Response.End and abandon the rest of the page. In fact, IIS 5.0 codifies this practice—whenever ASP is about to execute a new request, it checks to see how long the request has been in the queue. If it has been there for more than 3 seconds, ASP will check to see if the client is still connected and immediately terminate the request if it's not. You can use the AspQueueConnectionTestTime setting in the metabase to adjust this timeout of 3 seconds.

    If you have a page that takes a very long time to execute, you may also want to check Response.IsClientConnected at intervals. When response buffering is enabled, it is a good idea to do Response.Flush at intervals to give the user the impression that something is happening.

    Note On IIS 4.0, Response.IsClientConnected will not work correctly unless you first do a Response.Write. If buffering is enabled, you'll also need to do a Response.Flush. On IIS 5.0, there is no need for this—Response.IsClientConnected works fine. In any case, Response.IsClientConnected has some costs, so only use it before an operation that takes at least, say 500 milliseconds (that's a long time if you're trying to sustain a throughput of dozens of pages per second). As a general rule of thumb, don't call it in every iteration of a tight loop, such as when painting the rows of a table—perhaps every 20th or 50th row of the table, instead.


    example:

    Code:
     
    <%@ LANGUAGE="VBSCRIPT" %> 
    <%
     Function IsConnectedAfter(Seconds) 
      Dim StartTime 'time the function started 
      Dim PauseTime 'time the pause loop started
     
     'Use PerfMon to monitor the CPU cycles on the Web server. You
     'will notice that if you click STOP in the browser, the CPU
     'will settle down sooner than if the loop had continued.
     
     IsConnectedAfter = True 
    StartTime = Now 
    Do While DateDiff("s", StartTime, Now) < Seconds 
      PauseTime = Now Do While DateDiff("s", PauseTime, Now) < 1 
    	 'Do Nothing.
    	Loop 
    	Response.Write "." 
       If Response.IsClientConnected = False Then 
    	  IsConnectedAfter = False 
    		Exit Function End If Loop End Function 
    %> 
    <HTML>
     <HEAD>
     <META NAME="GENERATOR" Content="Microsoft Visual InterDev 1.0">
     <META HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1"> 
    <TITLE>Document Title</TITLE></HEAD>
    <BODY>
       <H1>!!! WARNING !!!</H1>
    	<P>This page has code in it that may use <B>100% CPU cycles</B> for at least 30 seconds. 
    		 Do not run this code on a production server. Restrict its use to a test server.<P>
    		Use SysMon to monitor the CPU cycles on the Web server. Press STOP in the Web browser, 
    		and you will see that the CPU cycles will settle down sooner than they would have without checking
    		the IsClientConnected property.<HR>
     
    <% 
       If IsConnectedAfter(30) then 
    	  Response.Write "<P>The client is still connected</P>" 
       Else 
     
    	'The browser is no longer connected. This would be a 
    	'good place to abort any transactions, clean up any
    	'variables, and so forth. 
    End If
    %>
    </BODY>
    </HTML>
    Last edited by bslintx; July 15th, 2005 at 08:43 PM.
  12. #22
  13. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Organizing Application Directories and Files


    Using a model /directory structure will help you establish consistency, security, and ease of maintenance.

    [Root Dir]--Application_Name
    The application root directory name should clearly convey the theme of the site. For example, an application for financial research might be named /Financial_Research. Avoid application root names that might be misidentified as standard subdirectories of a site, such as /Media or /Content. Also, avoid names that read like part numbers or codes, such as /FR98346A.To avoid adversely affecting production sites, develop the application in a development test environment. An easy way to do this is to develop new applications under the IIS HTTP root directory, /InetPub/wwwroot, then move them to the same directory under /InetPub/wwwroot in the production environment when they are ready.The root directory of every application should contain at least these files
    --Default.htm
    --Global.asa
    The file Global.asa specifies event scripts, declares objects that have application or session scope, and
    declares type libraries. For example, Global.asa scripts make application- and session-scope variables
    available at startup. Global.asa must be stored in the application root directory

    /Classes
    Classes directory holds Java classes used by the application

    /Content
    The /Content directory holds all pages (except Default.htm) and media that might be retrieved by a user
    of the site.

    /ASP
    The /ASP subdirectory of /Content contains all pages with server-side scripting. This directory must
    contain execute permissions so that ASP can execute the page scripts; storing all scripted pages here
    simplifies permissions management and site security.

    /HTM
    The /HTM subdirectory of /Content holds all pages containing only standard HTML. This directory is read-
    only and does not have execute permissions. A page containing server-side scripts that is stored here will
    not execute.

    /Images
    The /Images subdirectory of /Content contains graphics that are used independently of theme-related
    images, such as standard buttons and icons.

    /Media
    The /Media subdirectory of /Content contains subdirectories for audio, images, animation files, .avi files,
    and similar items used throughout the application

    /Themes
    The /Themes subdirectory of /Content is used in order to enable application-wide changes to the look of a
    site. The subdirectory contains style sheets, bullets, buttons, icons, rules, and similar items, and should be
    organized so that you can easily change the look of an application by modifying any or all the theme-
    related items. Each item in the /Themes subdirectory can be linked dynamically by setting an application
    variable to its virtual path.

    /Data (not in site directory)
    The /Data directory contains all database access information such as SQL scripts, file­based dataset names
    or similar data needed by the application. Do not place this directory under the site directory, as this could
    enable an unauthorized user to access business rules and private data.

    /DLLs (not in site directory)
    The /DLLs directory contains Microsoft® Component Object Model (COM) components and Microsoft®
    Visual Basic® 6.0 run-time DLLs, such as Vbrun500.dll and Msvbvm50.dll. Do not place this directory under
    the site directory, as this could enable an unauthorized user to access business rules and private data.

    /Helper_Files
    Helper files are server-side include files or text files that make HTML-coded information available across the
    application. For security reasons, the directory containing helper files should not be stored in the published
    Web space (the Web site directories identifiable to users).
    Last edited by bslintx; May 6th, 2005 at 03:19 AM.
  14. #23
  15. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Combine multiple sequential Response.Write lines


    Slow: (one per line)
    Code:
    Response.Write Name & "<br>"
    Response.Write Street & "<br>"
    Response.Write City & ", " & State & ", " & Zip & "<br>"
    A little faster (de-reference the object) :
    Code:
    With Response
    	.write Name & "<br>"
    	.write Street & "<br>"
    	.write City & ", " & State & ", " & Zip & "<br>“
    End With
    Faster: (Concatenate strings)
    Code:
    Dim strHTML
    strHTML = strHTML & Name & "<br>"
    strHTML = strHTML & Street & "<br>"
    strHTML = strHTML & City & ", " & State & ", " & Zip & "<br>“
    Response.Write strHTML
    Faster Still (Use continuation character):
    Code:
    Response.Write Name & "<br>" & _
    Street & "<br>" & ", " & _
    State & ", " & _
    Zip & "<br>"
    Even Faster (all on one line):
    Code:
    Response.Write Name & "<br>" & Street & "<br>" & ", " & State & ", " & Zip & "<br>"
  16. #24
  17. Moderator From Beyond
    ASP Mastermind (5000+ posts)

    Join Date
    Sep 2004
    Location
    Israel
    Posts
    31,135
    Rep Power
    2925
    nice thread, fit for sticky in my opinion. keep up the good job!!
  18. #25
  19. Contributing User
    ASP Scholar (3000 - 3499 posts)

    Join Date
    Jun 2004
    Posts
    3,072
    Rep Power
    194
    Use meaningful variable names to clearly show what type of data the variable should hold:
    Code:
    date_Birthday
    str_Label
    int_Number
    lng_BigNumber
    http://www.MapDays.com | Find events wherever, whenever you want them

  20. #26
  21. No Profile Picture
    Contributing User
    ASP Discoverer (100 - 499 posts)

    Join Date
    Apr 2005
    Location
    UK
    Posts
    165
    Rep Power
    14
    Originally Posted by bslintx
    Consider using the MapPath method instead of literal paths in ASP applications. The ASP Server.MapPath method allows you to physically relocate an ASP application without recoding scripts. This saves program modification and maintenance effort.

    Note: Performance is affected slightly, because every time you use MapPath in a script, IIS must retrieve the current server path. Consider placing the result of the method call in an application variable in order to avoid retrieving the server path.

    Code:
     
    Set objConn = Server.CreateObject("ADODB.Connection")
    Set objRS = Server.CreateObject("ADODB.Recordset") 
    FilePath = Server.MapPath("myDb.mdb")
    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & ";" 
    objConn.Open strConn
    I posted a thread a while ago with sample code about Database connection strings using the global.asa file. Click here to see the thread.

    Good work bslintx! I enjoy trawling through this thread.

    hmm... can I post this message?
    Last edited by matthuxtable; May 7th, 2005 at 04:10 PM. Reason: Forgot to put URL to Sample Database Connection Strings Code into post.
  22. #27
  23. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Type Notation


    Use proper Hungarian notation for variables and objects. The purpose of Hungarian notation is to be able to interpret the type and purpose of a variable. For local and public variables use mixed case of an initial lowercase Hungarian prefix followed by at least one uppercase letter

    Hungarian table examples:



    Last edited by bslintx; August 11th, 2005 at 10:32 PM.
  24. #28
  25. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Use good script coding style


    • Indent blocks of code
    • Use blank lines around blocks
    • Declare one variable per line (faster) and document variables
    • Use comments when required to document tricky or unusual code sections
  26. #29
  27. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Avoid context switching


    • Context switching occurs every time the switch is made between vbScript and HTML code blocks. Each context switched requires a significant amount of time and resources on the server.
    • Following the previous rule extensive use of <% =VariableName %> should be avoided as well.
    • Pool or combine small blocks together to make larger blocks of HTML and script.
    • Avoid switching script types e.g. between vbScript and jScript as this context swap is very expensive as the number of precompiled pages in the cache is limited



    inefficient example:
    Code:
    <table>
    <% For Each fld in rs.Fields %>
        <th><% = fld.Name %></th>
    <%
    Next
    While Not rs.EOF
    %>
      <tr>
      <% For Each fld in rs.Fields %>
         <td><% = fld.Value %></td>
       <% Next
      </tr>
       <% rs.MoveNext
    Wend %>
    </table>

    efficient example:

    Code:
    <table>
    <%
      For each fld in rs.Fields
          Response.Write ("<th>" & fld.Name & "</th>" & vbCrLf)
      Next
      While Not rs.EOF
        Response.Write ("<tr>")
        For Each fld in rs.Fields %>
          Response.Write("<td>" & fld.Value & "</td>" & vbCrLf)
        Next
        Response.Write "</tr>"
      Wend
    %>
    </table>

    Comments on this post

    • slackey05 agrees
    Last edited by bslintx; July 15th, 2005 at 08:47 PM.
  28. #30
  29. Contributing User
    ASP Skiller (1500 - 1999 posts)

    Join Date
    Apr 2004
    Location
    United States
    Posts
    1,814
    Rep Power
    17

    Use buffering


    <LI>For IIS4 (where buffering is off by default) Use Response.Buffer = True on all ASP pages.

    1. Buffering increases performance by decreasing the number of "writes" to the client

    • Allows the page to be redirected in case of an error.
    • However, be wary of un-moderated buffering on time consuming pages with large outputs (such as large tables).
    • In buffered output you can use Response.IsClientConnected after the first Response.Flush to test to see if the client is still there, and abort by using Response.End if not. Warning: for IIS4 and below the IsClientConnected call may return incorrect values unless some information has been flowed to the client.
    • Strategic use of Response.Flush can keep pages from timing out. For large tables, it may be necessary to additionally end and restart the table.
    For example:
    Code:
    lngRowCount = 0
    Response.Write "<table width='100%'>"
    while not rs.eof 
    	lngRowCount = lngRowCount + 1
    	if lngRowCount Mod 100 = 0 then 
    		Response.Write "</table>"
    		Response.Flush
    		Response.Write "<table width='100%'>"
    	end if
    
    	'Write out row
    
    wend

Similar Threads

  1. ASP and SQL
    By nofriends in forum Code Bank
    Replies: 12
    Last Post: October 14th, 2008, 01:56 PM
  2. Exception Handling
    By kirandayalin in forum ASP Development
    Replies: 14
    Last Post: April 21st, 2005, 01:16 PM
  3. combine SQL statements
    By leuvenaar in forum ASP Development
    Replies: 3
    Last Post: April 19th, 2005, 06:59 AM
  4. Replies: 3
    Last Post: January 14th, 2005, 02:38 PM
  5. Replies: 2
    Last Post: February 11th, 2004, 02:51 PM

IMN logo majestic logo threadwatch logo seochat tools logo