24 ASP tips for improving performance and styling 1th/2 page _ Application Tips

Source: Internet
Author: User
Tags connection pooling error handling odbc connection serialization sessions time interval xml parser server memory
Cheung-Fine content:
Brief introduction

Tip 1: Caching common data on a WEB server

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

Tip 3: Caching Data and HTML on a WEB server disk

Tip 4: Avoid caching inflexible components in application or Session objects

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

Tip 6: Magical Session Objects

Tip 7: Encapsulate code in a COM object

Tip 8: Get resources later and release resources early

Tip 9: Out-of-process execution will sacrifice reliability

Tip 10: Explicit Use options

Tip 11: Use local variables in subroutines and functions

Tip 12: Copy common data to a script variable

Tip 13: Avoid redefining arrays

Tip 14: Use response buffering

Tip 15: Batch inline scripts and Response.Write statements

Tip 16: Use response.isclientconnected before you start a long task

Tip 17: Instantiate objects with <OBJECT> tags

Tip 18: Use the TypeLib binding of ADO objects and other components

Tip 19: Leverage your browser's ability to authenticate

Tip 20: Avoid string concatenation in loops

Tip 21: Enable browser and proxy caching

Tip 22: Use Server.Transfer instead of Response.Redirect whenever possible

Tip 23: Add a slash at the end of the directory URL

Tip 24: Avoid using server variables


--------------------------------------------------------------------------------

Brief introduction

Performance is an attribute. You need to design your performance in advance, or rewrite your application later. In other words, what is a good strategy for maximizing the performance of Active Server Pages (ASP) applications?

This article provides a number of tips for optimizing ASP applications and the Visual Basic (R) Script Editor (VBScript). Many pitfalls and flaws were discussed. The recommendations listed in this article have been tested on http://www.microsoft.com and other sites and are working properly. This article assumes that you have a basic understanding of ASP development, including for VBScript and/or JScript, ASP application, ASP sessions, and other ASP internal objects (requests, responses, and servers).

ASP's performance, usually depends not only on the ASP code itself. We do not want to include all the wisdom in an article, but only at the end of the list of resources related to performance. These links include ASP and non-ASP topics, including ActiveX (R) Data Objects (ADO), part object Model (COM), databases, and Internet Information Server (IIS) configurations. These are our favorite links-be aware of them.

Tip 1: Caching common data on a WEB server

A typical ASP page retrieves data from the back-end database and then converts the result to Hypertext Markup Language (HTML). Retrieving data from memory is much faster than retrieving data from a back-end database, regardless of the speed of the database. Reading data from a local hard disk is often much faster than retrieving data from a database. As a result, you can often improve performance by caching data on a WEB server (in memory or disk).

Caching is a typical tradeoff between space and time. If you cache the data appropriately, you will see a dramatic improvement in performance. To make the cache work, it must maintain data that is frequently reused, and the cost of recalculation of the data is expensive or more expensive. If the cache is full of garbage data, it is a waste of memory.

Data that is infrequently changed is also a cached candidate because you do not have to worry about synchronizing data with the database. combo boxes, reference tables, DHTML fragments, Extensible Markup Language (XML) strings, menu items, and site configuration variables, including data source names (DSNs), Internet Protocol (IP) addresses, and Web paths) are cached candidate data. Note that you can cache the representation of the data rather than the data itself. If ASP pages do not change frequently and the cost of caching is very high (for example, the entire product catalog), consider generating HTML beforehand, rather than redrawing each request.

Where should the data be cached, and what caching policies are there? Data is often cached on Web server memory or on a Web server disk. The following two tips discuss these options.

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

ASP Application and Session objects provide a convenient container for caching data in memory. You can either give the data to the Application object or assign the data to the session object, which will remain in memory in the HTTP call. Session data is stored by user, and application data is shared among all users.

When will data be loaded into application or session? Typically, the data is loaded when the application or session is started. To load data at application or session startup, add the appropriate code in the following two functions:
Application_OnStart ()
Or
Session_OnStart ()
。 These two functions should be in Global.asa, and if not, you can add these functions. You can also load data the first time you need it. To do this, add some code (or write reusable script functions) to the ASP page that checks for the existence of the data and loads the data when it does not exist. This is an example of a classical energy technique called lazy Computing-no calculation before you really need it. Take a look at the example:

<%
Function getemploymentstatuslist
Dim D
D = Application ("Employmentstatuslist")
If d = "" Then
' Fetchemploymentstatuslist function (not shown)
' Fetch data from DB, return array
D = fetchemploymentstatuslist ()
Application ("employmentstatuslist") = d
End If
Getemploymentstatuslist = d
End Function
%>

You can write similar functions for each piece of data that you want.

What format should the data be stored in? Any variable type can be stored, because all script variables are different. For example, you can store strings, integers, or arrays. Typically, you will store the contents of an ADO recordset as one of these variable types. To get data derived from an ADO recordset, you can manually copy the data into a VBScript variable, one field at a time. Using an ADO recordset to preserve Functions GetRows (), GetString (), or Save () (ADO 2.5) is faster and easier. The full and detailed content is beyond the scope of this article. The following demo function uses the
GetRows ()
To return an array of recordset data:

' Fetch Recordset, return with 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 () ' Returns data as an array
Rs. Close
Set rs = Nothing
End Function

Further improvements to the above example should be to cache the HTML of the list, rather than caching the array. The following is a simple example:

' Take the recordset and return it in the HTML options 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 bindings
Do Until Rs. Eof
' The following line violates the need for string concatenation,
' But that's OK because we're building a cache
s = S & "<option>" & Fldname & "</option>" & VbCrLf
Rs. MoveNext
Loop
s = S & "</select>" & VbCrLf
Rs. Close
Set rs = Nothing ' See early release
Fetchemploymentstatuslist = S ' returns data as a string
End Function

In normal circumstances, you can cache the ADO recordset itself in the application or session scope. There are two warnings:

ADO must be a free thread for marking
You must use a disconnected recordset.
If you are not guaranteed to meet both requirements, do not cache the ADO recordset. In the following inflexible components and do not cache connection tips, we will discuss the dangers of storing COM objects in the application or session scope.

If you store data in a application or session scope, the data remains there until you change it in your program, session expiration, or WEB application restarts. What does the data need to be updated to handle? To force the application data to be manually updated, you can invoke data that is only accessible to the administrator to update the ASP page. In addition, the data can be automatically refreshed periodically through functions. The following example stores a timestamp with cached data and refreshes the data after a specified interval.

<%
' Error handling not shown ...
Const update_interval = 300 ' Refresh time interval, in seconds

' function returns the list of employment status
Function getemploymentstatuslist
Updateemploymentstatus
Getemploymentstatuslist = Application ("Employmentstatuslist")
End Function

' Periodically update cached data
Sub updateemploymentstatuslist
Dim D, Strlastupdate
Strlastupdate = Application ("Lastupdate")
If (strlastupdate = "") Or _
(Update_interval DateDiff ("s", Strlastupdate, now) Then

' Note: There may be two or more calls here. It's okay, it's just
' Generates a few unnecessary commands (there is a workspace for this)

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

' Update the Application object. With Application.Lock ()
' To ensure consistent data
Application.Lock
Application ("employmentstatuslist") = d
Application ("lastupdate") = CStr (now)
Application.UnLock
End If
End Sub

For other examples, see the fastest list box with application data.

Note that caching large arrays in a session or Application object is not the best policy. Before accessing an array element, the scripting language syntax requires that a temporary copy of the entire array be established. For example, if you cache a string array that maps a U.S. ZIP code to a local weather station in the Application object, which has 100,000 elements, the ASP must copy all 100,000 weather stations to a temporary array before it finds a string. In this case, it might be better to create a custom component with a custom method to store the weather station-or use a dictionary component.

Please don't pour the child out with the bath water. A new note to this view is that arrays provide fast lookup and storage of adjacent key-data pairs in memory. Index dictionary peso array is slow. You should choose the data structure that provides the best performance based on the circumstances.

Tip 3: Caching Data and HTML on a WEB server disk

Sometimes, too much data is not cached in memory. "Excess" is a qualitative judgment, depending on the amount of memory that is intended to be consumed, as well as the number of cached items and how often these items are retrieved. In summary, if you have too much data to cache in memory, consider caching the data on the WEB server's hard disk in the form of text or XML files. You can combine cached data on disk with cached data in memory to establish an optimal caching strategy for your site.

Note that when you measure the performance of a single ASP page, retrieving data on disk is not necessarily faster than retrieving data from the database. However, caching eases the load on the database and the network. In a high load situation, this will significantly increase the overall volume of traffic. Caching is very effective when querying the results of cached queries at high cost, such as multiple-table unions or complex stored procedures, or caching large result sets. According to the Convention, test the competition scheme.

ASP and COM provide several tools for building disk caching scenarios. The Save () and Open () functions of the ADO Recordset, which save and load the recordset on the disk. You can use these methods to override the example code in the above application data caching techniques, replacing the code that writes data to the Application object with the Save () file.

There are other components that work with files:

Scripting.FileSystemObject enables you to create, read, and write files.
MSXML is a Microsoft (R) XML parser provided with Internet Explorer that supports saving and loading XML documents.
The LookupTable object (an example used on MSN) is a good choice to load a simple list from disk.
Finally, consider caching the representation of the data on disk, rather than the data itself. Prefabricated HTML can be stored on disk as. htm or. asp files, and hyperlinks can point directly to these files. You can automate the HTML generation process by using business tools such as Xbuilder or the Internet Publishing feature of Microsoft (R) SQL Server. In addition, you can #include an HTML fragment to an. asp file. You can also use FileSystemObject to read HTML files from disk or to use XML for early tuning (English).

Tip 4: Avoid caching inflexible components in application or Session objects

While caching data in application or session objects is a good idea, caching COM objects can be a serious flaw. Embedding common COM objects into application or session objects is usually appealing. Unfortunately, many COM objects, including COM objects written in Visual Basic 6.0 or earlier, can cause serious bottlenecks when stored in application or session objects.

In particular, any inflexible component that caches in session or application objects can cause performance bottlenecks. Flexible components are marked as
Threadingmodel=both
Component (it aggregates the free thread aggregator (FTM)) or is marked as
Threadingmodel=neutral
Components (Windows (R) 2000 and COM + are new "neutral" models.) The following components are non flexible:

Free threaded components (unless they gather FTM).
The unit thread component.
Single threaded component.
Configured components (Microsoft Transaction Server (MTS)/com+ libraries and server packages/applications) are not flexible components unless they are "neutral" threads. Unit thread components and other inflexible components are best suited to work with page scopes (that is, they are created and destroyed on a single ASP page).

In IIS 4.0, mark as
Threadingmodel=both
The components are considered flexible. In IIS 5.0, this is not enough. Components must not only be marked as Both, but must also be clustered FTM. The flexibility article explains how to make the C + + components written with the Activity Template Library aggregate FTM. Note that if the component caches interface pointers, the pointers themselves must be flexible or must be stored in the COM Global Interface Table (GIT). If you cannot recompile the Both thread component so that it aggregates FTM, you can mark the component as
Threadingmodel=neutral
。 Also, if you do not want IIS to perform a flexible check (so that you want the inflexible component to be stored in the application or Session scope), you can set the
AspTrackThreadingModel
For
True
。 Do not advocate change
AspTrackThreadingModel


If you are trying to store in a Application object
Server.CreateObject
The inflexible component created, IIS 5.0 generates an error. Can be used in Global.asa by using the
<object Runat=server scope=application ...>
Solve the problem, but do not advocate this, as this will lead to aggregation and serialization, as described below.

If caching is not a flexible component, what error will occur? The inflexible component cached in the Session object "locks" the conversation to an ASP worker thread. The ASP maintains a worker thread pool, which serves the request. Typically, the new request is handled by the first available worker thread. If the session is locked to a thread, the request will have to wait for the thread it is associated to become available. For example: You go into a supermarket, pick up some food, and then pay at number 3rd. Since then, every time you buy food in this supermarket, you have to always pay at number 3rd, even if there are fewer or no people at the other checkout desk.

Storing the inflexible components in the Applicaton scope can even have a more severe impact on performance. ASPs will have to create dedicated threads to run flexible, applicaton-scoped components. This will result in two kinds of consequences: all calls have to be pooled to the thread, and all calls are serialized. Pooling means that parameters have to be stored in a shared area of memory, expensive context switches are performed on the dedicated thread, the method of the component is executed, the result is pooled to the shared area, and another expensive context switch allows control to return to the original thread. Serialization means that all methods must run one by one (only one method can be run at the same time). Two different ASP worker threads cannot execute methods on shared components at the same time. This will kill the parallel mechanism, especially on multiprocessor computers. Worse, all of the inflexible, application-scoped components will share a thread ("Host STA"), so the impact of serialization is even worse.

Do you feel confused? Here we propose a few general rules. If you are writing objects with Visual Basic (6.0) or earlier, do not cache them in a application or Session object. If you do not know the threading model of an object, do not cache it. Instead of caching the inflexible objects, you should create and release them on each page. The object will run directly on the ASP worker thread, so that no collection or serialization will occur. If the COM objects are running in the IIS box, and if they do not take a long time to initialize and cancel, the performance will be sufficient. Note that you do not use a Single-threaded object with this method. Be careful: VB can create a single-threaded object! If you have to use single-threaded objects (such as Microsoft Excel spreadsheets) in this way, do not expect high throughput.

Caching an ADO recordset is safe when ADO is marked as a free thread. To mark ADO as a free thread, use the Makfre15.bat file, which is typically located in the following directory: \\Program Files\common\system\ado.

Warning: If you are using Microsoft Access as a database, you should not mark ADO as a free thread. In general, the ADO recordset must also be disconnected, and if you cannot control the site's ADO configuration (for example, you are a stand-alone software vendor [ISV], selling your WEB applications to customers and then managing their own configurations), it might be better not to cache the recordset.

The dictionary component is also a flexible object. LookupTable loads its data from a data file, and it is useful for combo box data and configuration information. The Pagecache object from Duwamish books provides the directory semantics, as does the performance of Caprock Dictionary. These objects or their derived objects can form the basis of a valid caching policy. Note that the Scripting.Dictionary object is not flexible, so it should not be stored in the application or session scope.

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

Caching ADO connections is usually a bad strategy. If a Connection object is stored in application and used on all pages, all pages will compete to use the connection. If the Connection object is stored in the ASP session object, a database connection is created for each user. This will destroy the benefits of connecting pools and create unnecessary pressure on WEB servers and databases.

Instead of caching a database connection, you create and cancel an ADO object on each ASP page that uses ADO. This is a valid method because IIS has a built-in database connection pool. More specifically, IIS automatically enables OLE DB and ODBC connection pooling. This ensures that the connections on each page are created and canceled to be valid.

Because the connected recordset stores a reference to the database connection, you should not cache the connected recordset in the application or Session object. However, you can safely cache a disconnected recordset because it does not contain a reference to its data connection. To disconnect a recordset, perform the following two steps:

Set rs = Server.CreateObject ("ADODB.") RecordSet ")
Rs. CursorLocation = adUseClient ' 1th step

' Implanted record sets with data
Rs. Open strquery, Strprov

' Now disconnect the recordset from the data provider and the data source
Rs. ActiveConnection = Nothing ' 2nd step

For more information about connection pooling, see ADO and SQL Server (English) references.

Tip 6: Magical Session Objects

After affirming the benefits of caching in applications and Sessions, we recommend that you avoid using the Session object. As we'll talk about, Sessions has several drawbacks when it comes to busy sites. The so-called busy, usually refers to the site per second request hundreds of pages or at the same time thousands of users. This technique is more important for sites that must be scaled horizontally, that is, those that take advantage of multiple servers to accommodate load or perform fault tolerance. For smaller sites, such as intranet sites, the convenience of Sessions is also worthwhile compared to overhead.

To renovate, the ASP automatically creates a session for each user who accesses the WEB server. Each session has approximately a KB of memory overhead (the highest in any data stored in the session), and makes all requests slower. The session remains active until a configurable timeout (usually 20 minutes) is reached.

The biggest problem with session is not performance but scalability. A session cannot span a WEB server, and once it is created on a server, its data remains there. This means that if you use Sessions in the Web realm, you will have to design a policy for each user's request so that these requests are always directed to the server where the user's session is located. This is called "glue" the user to a WEB server. The term "sticky session" is derived from this. Because the session is not persisted to disk, the "stuck" user loses their Sessions status when the Web server crashes.

Strategies for implementing sticky sessions include hardware and software solutions. For example, the Network Load Balancing solution in Windows Advanced Server and Cisco's local pointer solution can implement sticky sessions at the expense of some scalability. These solutions are not perfect. We do not claim that you are now completely overturning your software solution (we have used ISAPI filters and URL straightening to check for scenarios).

Application objects also cannot span servers, and if you need to share and update application data within the Web realm, you need to use a backend database. But read-only application data is still useful in the Web realm.

If only to increase uptime (for handling failover and server maintenance), most sites that perform important tasks will need to deploy at least two Web servers. So, when designing an application that performs important tasks, you will need to implement a sticky session or simply avoid Sessions and any other state management technology that stores user state on a single WEB server.

If you are not currently using Sessions, be sure to turn them off. You can perform this operation for your application through Internet Services Manager (see the ISM documentation). If you decide to use Sessions, you can take a few ways to minimize the impact on performance.

You can move content that does not require Sessions, such as the help screen, visitor area, and so on, to a separate ASP application that is closed Sessions. You can prompt for ASP: You do not need a session object on a given page, and you use the following instructions at the top of the ASP page:

<% @EnableSessionState =false%>

A good reason to use this directive is that the session brings interesting problems to the frameset. The ASP guarantees that only one request from the session will be executed at any time. This ensures that if the browser requests multiple pages for a user, only one ASP request will enter the session at a time, which avoids multithreading problems when accessing the Session object. Unfortunately, as a result, all pages in the frameset are plotted in a serialized way, one after the other, not at the same time. In this way, the user may have to wait a long time to get all the frame content. This means: If some frames pages do not trust session, be sure to use
@EnableSessionState =false
Instructions to tell the ASP.

As an alternative to using the session object, there are many ways to manage session state. For small States (less than 4 KB), Cookies, querystring variables, and hidden forms are generally recommended. For a larger number of data, such as a shopping cart, using a back-end database is the most appropriate option. There is already a lot of information about state management techniques in the WEB server world. For more information, see Session state (in English).

Tip 7: Encapsulate code in a COM object

If you have a lot of VBScript or JScript, you can often improve their performance by moving the code to a compiled COM object. Compiled code usually runs faster than the interpreted code. Compiled COM objects can access other COM objects through early binding, and this method of invoking COM object methods is more efficient than "late binding" used by the script.

Encapsulating code in COM object species has the following benefits (beyond performance):

COM objects are a good way to separate the expression logic from the business logic.
COM object has code reuse enabled.
Many developers have found that code written in VB, C + +, or Visual J + + is easier to debug than ASP.
COM objects have some drawbacks, including initial development time and the need for different programming techniques. What you need to warn you about is that encapsulating the "less" amount of ASP can lead to performance degradation, not improvement. Typically, this occurs when a small amount of ASP code is encapsulated into a COM object. At this point, the overhead of creating and invoking COM objects exceeds the benefits of compiled code. It remains to be tested as to how ASP scripts and COM object code can be merged to produce the best performance. Note that Microsoft has dramatically improved script and ADO performance in Windows 2000/iis 5.0 compared to Windows NT (R) 4.0/iis 4.0. Thus, the performance advantages of compiled code for ASP code have been reduced with the introduction of IIS 5.0.

For more discussion on the pros and cons of using COM objects in ASP, see ASP Component guidelines and programming distributed applications with COM and Microsoft Visual Basic 6.0 (English). If you do deploy COM components, it is important to test them for strength. In fact, all ASP applications should be tested for strength as a formal process.

Tip 8: Get resources later and release resources early

It's a little trick. Usually, it is best to get resources later and release resources early. These resources include COM objects, file handles, and other resources.

ADO connectivity and Recordset are the primary goals of this optimization. When you are finished using the recordset, that is, after you print a table with its data, release it immediately, instead of waiting for the end of the page. Set your VBScript variable to
Nothing
Is the best way to do it. Do not leave the recordset simply out of scope. At the same time, any relevant Command or Connection object should be released. (Don't forget to call a Recordset or connection
Close ()
, when you set them to
= Nothing
Before. This shortens the time span that the database must adjust for you and releases the database connection to the connection pool as quickly as possible.
Current 1/2 page 12 Next read the full text
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.