One of the 28 ASP performance optimization rules proposed by Microsoft

Source: Internet
Author: User
Tags xml parser
Performance is a feature. You must design the performance in advance, or you will have to rewrite the application later. Program . That is to say, which of the following policies can optimize the performance of Active Server Pages (ASP) applications?

This article describes how to optimize ASP applications and Visual Basic & reg; Scripting Edition (VBScript. This article discusses many traps. The recommendations listed in this article have been tested in http://www.microsoft.com and on other sites, with remarkable results. This document assumes that you have a basic understanding of ASP development, including VBScript and/or JScript, ASP application, ASP session, and other ASP inherent objects (request, response, and server.

Generally, ASP performance mainly depends on ASPCodeMany other factors. We are notArticleAll information is listed. At the end of this article, we will list performance-related resources. These links cover ASP and non-Asp topics, including ActiveX & reg; Data Object (ADO), Component Object Model (COM), database, and Internet Information Server (IIS) configuration. These are some of our favorite links-be sure to check them out.

Tip 1: cache frequently used data on a Web server

A typical ASP page retrieves data from the back-end data storage, and converts the result to an ultra-Text Markup Language (HTML ). Regardless of the database speed, retrieving data from the memory is always much faster than retrieving data from the back-end data storage. Reading data from a local hard disk is usually faster than retrieving data from a database. Therefore, data can be cached on a Web server (stored in memory or disk) to improve performance.

Cache is a traditional practice of exchanging space for time. If the cached content is correct, you can see that the performance will be significantly improved. To make the cache effective, you must save frequently used data and re-calculate the data, which requires a high (moderate) overhead. If old data is cached, the memory will be wasted.

Data that does not change frequently is a good candidate for caching, because you do not have to worry about synchronizing the data with the database over time. Combo list, reference table, DHTML fragment, Extended Markup Language (XML) string, menu item, and site configuration variable (including data source name (DSN), Internet Protocol (IP) address and web path) are good cache candidates. Note that you can cache the "representation" of data instead of the data itself. If the ASP page is rarely changed and the cache overhead is large (for example, the entire product directory), you should consider generating HTML in advance instead of re-displaying each request in response.

Where should data be cached and what are the cache policies? Data is usually cached in the memory or disk of the Web server. The following two tips describe these two methods.

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

ASP application and session objects provide a convenient container for caching data in the memory. You can assign data to application and session objects, which are stored in memory between HTTP calls. Session data is stored separately by each user, while application data is shared among all users.

When will the data be loaded into the application or session? Generally, data is loaded when an application or session is started. To load data during application or session startup, add the appropriate code to application_onstart () or session_onstart. These functions should be in global. Asa. If not, you can add them. You can also load the data at the first time you need it. To this end, add some code (or write a reusable Script Function) to the ASP page to check whether the data exists. If not, load the data. This is a traditional performance technology called "inert computing"-it is not calculated until you know you need a value. For example:

<%
Function getemploymentstatuslist
Dim d
D = Application (? Employmentstatuslist ?)
If D = ?? Then
'Fetchemploymentstatuslist function (not shown)
'Fetches data from DB, returns an array
D = fetchemploymentstatuslist ()
Application (? Employmentstatuslist ?) = D
End if
Getemploymentstatuslist = d
End Function
%>

You can write similar functions for each required data block.

What format should data be stored? Any variant type can be stored, because all script variables are of a variant type. For example, you can store strings, integers, or arrays. Typically, you store the content of the ADO record set as one of these variable types. To obtain data from the ADO record set, you can manually copy the data to the VBScript variable, one field at a time. Using an ADO record set persistence function getrows (), getstring (), or save () (ADO 2.5) can speed up and make it easier. The details are beyond the scope discussed in this article. However, the following is a function example to illustrate how to use getrows () to return an array of record set data:

'Get recordset, return as an array
Function fetchemploymentstatuslist
Dim rs
Set rs = Createobject (? ADODB. recordset ?)
Rs. Open? Select statusname, statusid from employeestatus ?, _
? DSN = employees; uid = sa; Pwd = ;?
Fetchemploymentstatuslist = Rs. getrows ()? Return data as an array
Rs. Close
Set rs = nothing
End Function

Further improve the preceding example to cache HTML as a list instead of an array. The following is a simple example:

'Get recordset, return as HTML Option List
Function fetchemploymentstatuslist
Dim RS, fldname, S
Set rs = Createobject (? ADODB. recordset ?)
Rs. Open? Select statusname, statusid from employeestatus ?, _
? DSN = employees; uid = sa; Pwd = ;?
S =? <Select name = ?? Employmentstatus? & Vbcrlf
Set fldname = Rs. Fields (? Statusname ?) 'Ado field binding
Do until Rs. EOF
'Next Line violates don't do string concats,
'But it's OK because we are building a cache
S = S &? <Option>? & Fldname &? </Option>? & Vbcrlf
Rs. movenext
Loop
S = S &? </SELECT>? & Vbcrlf
Rs. Close
Set rs = nothing 'see release early
Fetchemploymentstatuslist = S' return data as a string
End Function

Under appropriate conditions, the ADO record set itself can be cached in the application or session scope. There are two warnings:

Ado must be marked as a free thread
The disconnected record set must be used.
If the two requirements cannot be met, do not cache the ADO record set. In the following "non-agile components" and "Do not cache connections" techniques, we will discuss the risks of storing COM objects in the application or session scope.

When you store data in the application or session scope, the data is retained until you change it programmatically, the session expires, or the web application restarts. What if data needs to be updated? To manually update application data, you can access ASP pages that only Administrators can access to update data. Alternatively, you can use the function to automatically refresh data on a regular basis. The following example stores the timestamp with cached data and refreshes the data after a period of time.

<%
'Error handing not shown...
Const update_interval = 300 'refresh interval, in seconds

'Function to return the employee status list
Function getemploymentstatuslist
Updateemploymentstatus
Getemploymentstatuslist = Application (? Employmentstatuslist ?)
End Function

'Periodically update the cached data
Sub updateemploymentstatuslist
Dim D, strlastupdate
Strlastupdate = Application (? Lastupdate ?)
If (strlastupdate = ??) Or _
(Update_interval <datediff (? S ?, Strlastupdate, now) then

'Note: Two or more CILS might get in here. This is okay and will simply
'Result In A Few unnecessary fetches (there is a workaround for this)

'Fetchemploymentstatuslist function (not shown)
'Fetches data from DB, returns an array
D = fetchemploymentstatuslist ()

'Update the application object. Use application. Lock ()
'To ensure consistent data
Application. Lock
Application (? Employmentstatuslist ?) = Events
Application (? Lastupdate ?) = CSTR (now)
Application. Unlock
End if
End sub

For more information, see world's fastest ListBox with application data.

It is not a good practice to cache large arrays in a session or application object. Before accessing any element of the array, the syntax of the script language requires that the entire array be copied temporarily. For example, if an array consisting of 100,000 elements in a string is cached in the Application object, ASP must copy all the 100,000 weather stations to a temporary array before extracting a string. In this case, it would be better to create a custom component using a custom method to store weather stations-or use a dictionary component.

Let's warn you not to drop the baby and bath water together: Arrays can be quickly searched and stored in memory as neighboring key data pairs. Indexing a dictionary peso to index an array is much slower. Select a data structure that provides the best performance based on your actual situation.

Tip 3: cache data and HTML on the disk of the Web Server

Sometimes, too much data may be stored in the memory. "Too many" is just a saying, it depends on how much memory you want to consume, the number of projects to be cached, and the frequency of retrieving these projects. In any case, if there is too much data to be cached in the memory, consider caching the data in text or XML files on the hard disk of the Web server. You can cache data on disks and memory at the same time to create the most appropriate Cache Policy for your site.

Note that when measuring the performance of a single ASP page, retrieving data on a disk may not necessarily be faster than retrieving data from a database. However, the cache will reduce the load on the database and the network. In the case of high load, this can greatly improve the overall throughput. This is very effective when the cache overhead is a large query result set (such as multi-table join or composite Stored Procedure) or a large result set. Test the advantages and disadvantages of several solutions as usual.

ASP and COM provide some tools for creating disk-based Cache solutions. The ADO record set save () and open () functions save and load the record set in the disk. You can use these methods to re-compile the code example in the preceding application data cache technique, and use the SAVE () of the file to replace the code written to the application object.

Some other components can be used for files:

Scripting. FileSystemObject allows you to create, read, and write files.
Microsoft & reg; XML Parser (MSXML) provided with Internet Explorer supports saving and loading XML documents.
Lookuptable objects (for example, used on MSN) are the best option to load a simple list from a disk.
Finally, you should consider caching the data representation on the disk, rather than the data itself. Pre-converted HTML files can be stored on disks using. htm or. asp files. Hyperlinks can direct to these files. You can use commercial tools such as xbuilder or Microsoft & reg; SQL Server to automate the HTML process. Alternatively, you can place HTML code snippets in The. asp file. You can also use FileSystemObject to read HTML files from the disk, or use XML for Early conversion.

Tip 4: Avoid caching non-agile components in application or session objects

Although caching data in application or session objects is a good practice, caching COM objects has a serious trap. In general, people tend to cache frequently used COM objects to application or session objects. Unfortunately, many COM objects (including all objects written in Visual Basic 6.0 or earlier) may cause serious bottlenecks when stored in application or session objects.

Specifically, when any inagile component is cached in the session or application object, it will cause a performance bottleneck. An agile component is a component marked as threadingmodel = both, which aggregates free-threaded virtualer (FTM); or is marked as a threadingmodel = neutral component. (The neutral model is a new model for Windows & reg; 2000 and COM + .) The following components are not agile:

Free-threaded components (unless they aggregate FTM ).
Unit thread component.
Single-threaded components.
The configured components (Microsoft Transaction Server (MTS)/COM + Library and server packages/applications) are not agile unless they are neutral threads. Unit thread components and other non-agile components are the most suitable in the scope of the page (that is, they are created and destroyed on a single ASP page ).

In IIS 4.0, Components Marked as threadingmodel = both are considered agile. In IIS 5.0, this is not enough. The component must not only be marked with both, but also be clustered with FTM. The article on Agility describes how to aggregate FTM with C ++ components written in the Active Template Library. Note that if the component caches interface pointers, the pointers must be agile or stored in the com shared interface table (GIT. If you cannot re-compile the both thread component to aggregate FTM, you can mark the component as threadingmodel = neutral. Alternatively, if you do not want IIS to perform a agility check (therefore, you can allow non-agile components to be stored in the application or session scope), you can set asptrackthreadingmodel to true in the configuration database. We do not recommend that you change the asptrackthreadingmodel.

If you want to store non-agile components created with server. Createobject in the Application object, IIS 5.0 will have an error. You can. <object runat = server scope = application...> avoid this error, but we do not recommend this because it will result in collection and serialization, which will be described below.

What will happen if you cache non-agile components? The non-agile component cached in the Session Object locks the session to the ASP worker thread. ASP maintains a worker thread pool to process requests. Generally, a new request is always processed by the first available worker thread. If the session is locked on a thread, the request must wait until the relevant thread is available. Here is an analogy that may be helpful: You go to a supermarket, select some items, and pay at the # _ 3 cashier. Then, whenever you pay for the goods in that supermarket, you always have to pay at the # _ 3 receiving desk, even if there are few or no other people waiting in line before the receiving desk, this is also true.

The impact of Storing non-agile components in the application scope on performance is even worse. ASP must create a special thread to run non-agile components stored in the application scope. There are two results: All calls must be aggregated into this thread, and all calls are lined up. "Aggregation" means that the parameters must be stored in the shared area of the memory; execute a context switch with high overhead to a special thread; execute the component method; and collect the results to the shared area; execute another context switch with high overhead and control the return to the original thread. Serialization means that only one method is run at a time. Two different ASP worker threads cannot execute multiple methods on the shared component at the same time. This eliminates concurrency, especially on multi-processor computers. Worse, all components in the non-Agile application scope share one thread (host Sta), so the effects of serialization are even more significant.

What do you do? Below are some general rules. If you write objects using Visual Basic (6.0) or earlier versions, do not cache them in application or session objects. If you do not know the thread model of the object, do not cache it. Instead of caching non-agile objects, you should create and release them on each page. Objects run directly on ASP worker threads, so they are not pooled OR serialized. If COM objects run on the IIS server and they are not initialized or deleted for a long time, the performance is acceptable. Note that single-threaded objects should not be used in this way. Be careful-VB can create a single-thread object! If you must use a single-threaded object (such as a Microsoft Excel spreadsheet) like this, do not expect high throughput.

When ADO is marked as a free thread, the ADO record set can be safely cached. To mark ADO as a free thread and use the makfre15.bat file, it is usually located in the \ Program Files \ common \ System \ ADO directory.

Warning if you use Microsoft Access as a database, do not mark ADO as a free thread. The ADO record set must also be disconnected. Generally, if you do not have control over the ADO configuration in the site (for example, you are an independent software vendor [isV] and sell web applications to customers who manage their own configurations ), it is best not to cache record sets.

Dictionary components are agile objects. Lookuptable loads its data from the data file, which can be used for the data and configuration information of the combo box. The pagecache object in duwamish books provides dictionary syntax, and caprock dictionary can also. These objects or their derived objects can form the basis of an effective Cache Policy. Note that the scripting. dictionary object is not agile and should not be stored in the application or session scope.


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.