How to enhance ASP program performance

Source: Internet
Author: User
Tags connection pooling iis microsoft sql server object model odbc connection sessions thread xml parser
Program | performance


Performance is a very important feature. You need to design the performance metrics beforehand, otherwise you'll have to rewrite the program for that. is to imagine how to optimize the implementation of ASP programs?

This paper presents some techniques for optimizing ASP application and VBScript, and many techniques and defects have been discussed. The recommendations listed here have been tested on http://www.microsoft.com and other sites and are working very well. This article assumes that you have the basics of ASP development, including VBScript or jscript,asp applications, ASP sessions, and other ASP built-in objects (Request,response and server).

Typically, the performance of an ASP is much more than just the ASP code itself! Performance-related resources are listed at the end of this article, which includes ASP and non-ASP parts, including ActiveX Data Objects (ADO), Component Object Model (COM), database, And the configuration of Internet Information Server (IIS). In addition to these, there are some very good links worth seeing.

Tip 1: Caching frequently used data on a Web server

Typically, an ASP page retrieves data from a background store and then forms the result in Hypertext Markup Language (HTML). Retrieving data from memory is much faster than from a background storage device, regardless of the speed of the database. Reading data from your local hard disk is usually very fast. Therefore, improving performance can be achieved by caching the data on the server, either by caching the data in memory or by the local hard drive.

Caching is the classic "space for Time" compromise. If the cache is properly cached, you can see significant performance improvements. In order for caching to be effective, it is necessary to ensure that cached data is often reused and computationally cumbersome. Caching a cache full of stale data is a waste of memory.

Data that is infrequently changed is a good object for caching because it does not need to be considered at any time when the data is updated for synchronization operations. combo boxes, reference tables, DHTML code, extended Markup language strings, menus, and site configuration variables (including data source name dsns,internet protocol address IP and Web path) are good caching objects. Note: You want to cache the data expression instead of the data itself. If an ASP page changes frequently and is laborious to cache (such as the entire product catalog), consider generating HTML instead of describing it every time a request occurs.

Tip 2: Cache frequently used data in application or session objects

The application and session objects in ASP are convenient containers for caching data in memory. You can assign data to application and session objects, which will remain in memory for the duration of the HTTP call. What is the data in the session? A user service, the data in the application is shared by all users.

When do I need to mount data in application and session? Typically, when the application starts or the session begins, the data is loaded. To load the data at this point, add the appropriate code to the application OnStart () or Session OnStart (). These functions are in the file Global.asa and are added if they do not exist. You can also call in when the data is needed for the first time, add code to the ASP page, check whether the data exists, and if it is not found, transfer it. Here is an example of what is called the "lazy evalution" classical processing technology: It is not calculated until it is needed. Examples are as follows:

$#@60;%function getemploymentstatuslist Dim d = Application ("Employmentstatuslist") If d = "" Then  fetchemployments Tatuslist function (not shown)  fetches data to DB, returns an Array D = fetchemploymentstatuslist () application ("Emp Loymentstatuslist ") = d end If getemploymentstatuslist = DEnd function%$#@62;
For different data, you can write a similar function code.

What format should the data be saved in? Any variable type can be, because all script variables are different. For example, you can save as a string, integer, or data. Typically, the contents of an ADO recordset are stored in one of these variable types. To extract data from an ADO recordset, you need to manually copy the data to a VBScript variable, one field at a time. Using a function of any ADO recordset functions GetRows (), GetString (), or Save () (ADO 2.5) is very fast and simple, and here's a function that describes how to use GetRows () to return an array of recordset data:
Get Recordset, return as a arrayfunction fetchemploymentstatuslist Dim rs  Set rs = CreateObject ("ADODB". Recordset ") Rs. Open "Select Statusname, Statusid from Employeestatus", _ "dsn=employees;uid=sa;pwd=;" Fetchemploymentstatuslist = Rs. GetRows () "Return to data as an Array Rs." Close Set rs = NothingEnd Function
A deeper technique for the above code is to cache HTML for the list. Here's a simple example:
Get Recordset, return as HTML Option listfunction fetchemploymentstatuslist Dim rs, fldname, s Set rs = CreateObject ("Adod B.recordset ") Rs. Open "Select Statusname, Statusid from Employeestatus", _ "dsn=employees;uid=sa;pwd=;" s = "$#@60;select name=" "Employmen Tstatus "$#@62" & vbCrLf Set fldname = Rs. Fields ("Statusname")  ADO Field Binding do Until Rs. EOF  Next Line violates Dont does String concats,  but its OK because we are building a cache s = S & "$#@60;opti on$#@62; "& Fldname &" $#@60;/option$#@62 & VbCrLf Rs. MoveNext Loop s = S & "$#@60;/SELECT$#@62;" & VbCrLf Rs. Close Set rs = "Nothing"  Early fetchemploymentstatuslist = s return  data as a stringend Function
In the right environment, the ADO recordset itself can be cached in application or session, but there are 2 hints:
    • ADO must be a free thread-flagged
    • Need to use the disconnected recordset method
If you cannot guarantee the above 2 conditions, do not cache the ADO recordset, because this can be very dangerous.

When you save the data in a application or session, the data remains until the program changes it, the session variable expires, or the Web application restarts. What if the data needs to be updated? You can call an ASP page that only an administrator can access to update the data or, periodically, automatically update the data through the function. In the following example, the clock tag is saved with the cached data, and the data is refreshed after a period of time.
$#@60;% error handing not shown ... Const update_interval = INTERVAL Refresh seconds Function to return the employment status Listfunction Getemploym Entstatuslist updateemploymentstatus getemploymentstatuslist = Application ("Employmentstatuslist") End Function Periodically update the cached datasub updateemploymentstatuslist Dim d, strlastupdate strlastupdate = Application ("LastU Pdate ") If (strlastupdate =" ") Or _ (Update_interval $#@60; DateDiff ("s", Strlastupdate, now) is Then note:two or more calls might get in. This is okay and would simply result in a few unnecessary fetches (there are a workaround for this) FETCHEMPLOYMENTSTATUSL ist function (not shown) fetches data to DB, returns an Array D = fetchemploymentstatuslist () Update the application O Bject. Use Application.Lock () to ensure consistent data Application.Lock application ("employmentstatuslist") = d Application ("L Astupdate ") = CStr (now) Application.UnLock End IfEnd Sub 
For another example, see World's fastest ListBox with application Data.

It is important to realize that caching a large array of arrays in a session or Application object is not a good idea. Before accessing any element in an array, the rules of the scripting language require that you first establish a temporary backup of the entire array. For example, if you cache an array of 100,000 elements in a Application object, It contains the U.S ZIP code and the local weather station correspondence, the ASP must first copy all 100,000 weather station information to the temporary array, then can select one of the strings to handle. In this case, it's a good way to create a custom component and write a method to store the weather station information.

Tip 3: Caching data and HTML pages on a Web server disk

Sometimes, there are "many" data to be cached in memory. "Many" are relative, depending on how much memory is consumed, how many items are cached, and how often the data is retrieved. In any case, if you need to cache a large amount of data in memory, consider caching on the Web server's hard disk in text or XML file format. Of course, you can also mix hard disk cache data and memory cache data to achieve optimal caching.

Note: When testing the performance of a single ASP page, retrieving data from the disk is not necessarily faster than retrieving the data from the network database, but caching reduces the call to the network database. This will significantly increase the throughput of the network when called on a large scale. Caching a time-consuming query result is useful, for example, for a complex stored procedure, or for a large number of result data.

ASP and COM provide several tools for creating disk-buffered configurations. The Save () and Open () functions of the ADO Recordset are responsible for saving and adjusting the recordset on disk. In addition, there are some components:
    • Scripting.FileSystemObject allows you to create, read, and write files
    • Msxml,microsoft XML Parser with Internet Explorer, support for saving and loading XML documents
    • LookupTable objects, such as those used on MSN, are a good choice to dial into a simple list from disk.
Finally, consider the expression that caches the disk data, not the data itself. preprocessed HTML can be stored as. htm or. asp files, and links point directly to them. You can automate these processes with business tools such as Xbuilder or Microsoft SQL Server Internet Publishing classes. Also, you can include an HTML program fragment in an. asp file. Similarly, you can use FileSystemObject to read HTML files from disk or use XML for early rendering to do this work.

Tip 4: Avoid caching non-brisk components in application or Session objects

Caching data in a application or Session object is a good way to do it, but there are serious flaws in caching COM objects. Caching frequently used COM objects in application or session objects This work is fascinating, but unfortunately, many COM objects, including object components written in Visual Basic 6.0 or previous versions, When stored in a application or Session object, a serious bottleneck problem occurs.

In particular, when the component is not written very lightweight, it is highly likely to have a bottleneck problem. A lightweight component is a component that marks the Threadingmodel=both, which aggregates the free thread arrangement (FTM) or marks the threadingmodel= Neutral (Neutral mode is a new feature in Windows2000 and COM +). The following components are not lightweight:
    • free-threaded components (unless they are assembled into FTM)
    • apartment-threaded components
    • single-threaded components
Configured components are not lightweight components unless they are neutral-threaded. apartment-threaded components and other lightweight components work well within the page range, which means they are created and released in a single ASP page.

What happens if you cache a component that is not lightweight? Non-lightweight components cached in the Session object will "lock" sessions. The ASP maintains a pool of work threads that responds to requests, and typically new requests are controlled by the first available worker thread. If a session is locked in a thread, the request is forced to wait until the relevant thread becomes available. Here's an analogy: you go to a supermarket, pick up some food, and pay at number 3rd. From then on, as long as you buy food in that supermarket, you will often go to the payment counter 3rd, although the other payers are less or even no one.

Tip 5: Do not cache a database connection in a application or Session object

Caching ADO connections is usually not a good strategy. If a connection object is stored in a Application object and is used on all pages, all pages will scramble for the connection's use. If stored in the ASP Session object, a database connection will be opened for each user. This will frustrate the usage intent of the connection pool and impose unnecessary high cost pressures on both the Web server and the database.

To override a cached database connection, you can create and release an ADO object in each ASP page that uses ADO. This is very effective because IIS has a built-in database connection pool. More precisely, IIS handles OLE DB and ODBC connection pools automatically, which ensures that the work of creating and releasing connections on each page is efficient.

Because the connected recordset stores references to the database connection, do not cache the connected recordset in the application or Session object. However, you can safely cache disconnected types of recordsets that do not hold references to the corresponding database connections. To disconnect the recordset, perform the following 2 steps:
adUseClient  Step 1  Populate the recordset with data Rs. Open strquery, Strprov now disconnect the recordset from the  data provider and data source Rs.  ActiveConnection = Nothing Step  2
For more information on connection pooling, visit the ADO and SQL Server.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.