Article 3 of the 28 code for ASP performance optimization proposed by Microsoft

Source: Internet
Author: User
Tags microsoft frontpage server memory

Tip 10: use explicit options

Option explicit should be used in the. asp file. This command is placed at the top of the. asp file, which forces developers to declare all variables to be used. ManyProgramThis method is very helpful for debugging applications, because it avoids the possibility of a key error variable name and a mistake in creating a new variable (for example, writing myxmlstring =) into myxlmstring = ....

More importantly, declared variables are faster than undeclared variables. Therefore, the script references the variable by name every time it uses an undeclared variable during running. On the other hand, declared variables are sequential, either at compile time or run time. Later, all declared variables are referenced in this order. Because option explicit forces variable declaration, it ensures that all variables are declared, so the access speed is fast.

Tip 11: use local variables in subroutines and functions

Local variables are those declared in subroutines and functions. In a function or subroutine, local variable access is faster than global variable access. Using local variables also causesCodeTherefore, use local variables whenever possible.

Tip 12: Copy frequently used data to script variables

When accessing the COM Object in ASP, copy frequently used object data to the script variable. In this way, the com method call can be reduced because the overhead of COM method call is relatively large compared with the Access Script variable. When accessing collection and dictionary objects, this technology also reduces the overhead of searching.

Generally, if you want to access object data more than once, you should put the data in the script variable. The main objective of this optimization is the request variable (Form and querystring variables ). For example, your site can pass a querystring variable named userid. Assume that this userid is referenced for 12 times on a specific page. You do not need to call request (? Userid ?) The USERID is assigned to a variable at the top of the ASP page 12 times. Then use the variable from start to end on the page. In this way, 11 com method calls are saved.

In fact, the overhead for accessing com properties or methods is not that large. The following example shows a fairly common code (in syntax ):

Foo. Bar. blah. Baz = Foo. Bar. blah. QAZ (1)
If Foo. Bar. Blah. zaq = Foo. Bar. blab. ABC then '...

When this code is run, the following is the case:

The Foo variable is parsed as a global object.
The variable bar is parsed as a member of foo. This is actually a com method call.
The variable blah is parsed as a member of foo. Bar. This is another com method call.
The variable QAZ is parsed as a member of foo. Bar. Blah. No error. This is still a com method call.
Call Foo. Bar. Blah. Quaz (1 ). Call the com method again. Do you understand?
Repeat steps 1 to 3 to parse Baz. The system does not know whether to call QAZ to change the object model. Therefore, you must perform steps 1 to 3 again to parse Baz.
Resolve Baz to a member of foo. Bar. Blah. Assign attributes.
Execute steps 1 to 3 again to parse zaq.
Execute steps 1 to 3 again to parse ABC.
As you can see, the efficiency is quite poor (and slow ). The quick way to write this code using VBScript is:

Set myobj = Foo. Bar. blah' do the resolution of blahonce
Myobj. Baz = myobj. QAZ (1)
If myobj. zaq = myobj. ABC then '...

If you use VBscript 5.0 or later, you can use the with statement to write this Code:

With Foo. Bar. Blah
. Baz =. QAZ (1)
If. zaq =. ABC then '...
...
End

Note that this technique is also applicable to VB programming.

Tip 13: avoid re-determining the array dimension

Avoid redim arrays whenever possible. In terms of performance, if the physical memory size of the computer is limited, it is best to set the initial dimension of the array to its most unfavorable condition-or set the dimension to its optimal condition, then re-determine the dimension as needed. This does not mean that if you know that you do not need memory, you can allocate a few megabytes of memory.

The following code shows you how dim and redim are used improperly.

<%
Dim myarray ()
Redim myarray (2)
Myarray (0) =? Hello?
Myarray (1) =? Good-bye?
Myarray (2) =? Farewell?
...
'Some other code where you end up needing more space happens, then...
Redim preserve myarray (5)
Myarray (3) =? More stuff?
Myarray (4) =? Even more stuff?
Myarray (5) =? Yet more stuff?
%>

It is better to correct the initial size dim of the array at the beginning (in this example, It is 5) to make it much better than the redim array. You may waste some memory (if you do not use all the elements), but the advantage is that the speed becomes faster.

Tip 14: Use response Buffering

You can enable "response Buffering" to buffer the entire page to be output. In this way, the amount of data written to the browser is minimized to improve the overall performance. Each write operation generates a large amount of system overhead (in IIS and the amount of data sent over the network). Therefore, the fewer write operations, the better. It is slow to start and uses naglingAlgorithm(To reduce network congestion), TCP/IP is much more efficient when sending large data blocks than when many small data blocks must be sent.

There are two ways to enable response buffering. First, you can use Internet Services Manager to enable response buffering for the entire application. We recommend that you use this method. in IIS 4.0 and IIS 5.0, the new ASP application enables response buffering by default. Second, you can add the following code lines near the top of each ASP page to enable response buffering:

<% Response. Buffer = true %>

This line of code must be executed before any response data is written to the browser (that is, before any HTML appears in the ASP script and before any cookies are set using the response. Cookies set ). In general, it is best to enable response buffering for the entire application. In this way, you do not have to write the above Code lines at the top of each page.

Response. Flush
There is a common complaint about response buffering, that is, users feel that the response speed of ASP pages is slow (even if the overall response time is improved), because they have to wait until the entire page is generated, then they can see things. For pages with long running time, you can set response. buffer to false to disable response buffering. However, a better strategy is to use the response. Flush method. This method sends all HTML converted by ASP to the browser. For example, ASP can call response after converting the first 1,000 rows of a table with 100 rows. flush, force the conversion result to the browser so that the user can see the first 100 rows before the remaining rows are ready. This technology can perfectly combine the Response Buffer with the browser's gradual display of data.

(Note that in the example of the above 1,000 rows table, many browsers do not show the table before they see the close </table> mark. Check whether your target browser supports this function. To avoid this situation, the table is divided into multiple tables with fewer rows and response. Flush is called after each table. Earlier versions of Internet Explorer show the table before the table is completely downloaded. If you specify the table width, the display speed will be extremely fast, this avoids forcing Internet Explorer to calculate the column width by measuring the content width of each cell .)

Another common complaint about response buffering is that when a very large page is generated, it will occupy a lot of server memory. Regardless of the method for generating large pages, this problem can also be solved by clever use of response. Flush.

Tip 15: batch processing embedded scripts and response. Write statements

VBScript syntax <% = expression %> writes the value of "expression" to the ASP output stream. If the response buffer is not enabled, every statement in the buffer writes data to the browser over the network with many small packets. This is slow. In addition, interspersed execution of a small amount of scripts and HTML will lead to switching between the script engine and HTML, thus reducing performance. Therefore, use the following technique: Use response. Write to call instead of bundled nested expressions. For example, in the following example, each field in each row has a write operation on the Response stream, and each line has many switches between VBScript and HTML:

<Table>
<% For each failed in RS. Fields %>
<TH> <% = signature. name %> </Th>
<%
Next
While not Rs. EOF
%>
<Tr>
<% For each failed in RS. Fields %>
<TD> <% = gradient. Value %> </TD>
<% Next
</Tr>
<% Rs. movenext
Wend %>
</Table>

The following code is more effective. Each row has a write operation on the Response stream. All code is included in a VBScript block:

<Table>
<%
For each errors in RS. Fields
Response. Write (? <TH>? & Region. Name &? </Th>? & Vbcrlf)
Next
While not Rs. EOF
Response. Write (? <Tr> ?)
For each errors in RS. Fields %>
Response. Write (? <TD>? & Variable. Value &? </TD>? & Vbcrlf)
Next
Response. Write? </Tr>?
Wend
%>
</Table>

This technique is especially effective when response buffering is disabled. It is best to enable response buffering and check whether the batchcompute response. Write helps improve performance.

(In this particular example, creating a nested loop (while not Rs. EOF...) of the table subject can be replaced by a carefully constructed getstring call .)

Tip 16: If the page takes a long time to complete, use response. isclientconnected before execution.

If users are impatient, they may discard the ASP page before you start to execute their requests. If they click Refresh or move to another page on the server, there is a new request waiting at the end of the ASP Request queue, and there is a disconnect request in the middle of the queue. When the server load is very high (so the Request queue will be very long and the response time will also get longer), this situation will often occur, which can only make the situation worse. If the user no longer connects, it makes no sense to execute ASP pages (especially slow and large ASP pages. You can use the response. isclientconnected attribute to check this situation. If false is returned, call response. End and discard the rest of the page. In fact, IIS 5.0 has compiled this practice into a program-whenever ASP is about to execute a new request, it will check how long the request has been waiting in the queue. If you have waited for more than 3 seconds, ASP checks whether the client is still connected. If no connection is available, the request is terminated immediately. You can use the aspqueueconnectiontesttime setting in the configuration database to change the timeout value from 3 seconds to another value.

If the page takes a long time to complete, you can also check response. isclientconnected from time to time. When response buffering is enabled, it is best to execute response. Flush from time to let the user know what is going on.

Note: on IIS 4.0, response. Write is executed first, otherwise response. isclientconnected will not work properly. If buffering is enabled, you must also execute response. Flush. -Response. isclientconnected works normally. Response. isclientconnected has some overhead, so it takes at least (for example) 500 milliseconds for an operation (if you want to maintain the throughput of dozens of pages per second, this is a long time). Experience shows that you should not call it every time you repeatedly execute a tight loop. For example, it may be appropriate to show many rows in the table-call at every 20 or 50 rows.

Tip 17: Use <Object> to mark the example object

If you want to reference objects that are not in all code paths (especially objects in the server or Application Scope), use global. the <object runat = server id = objname> flag in ASA declares them without using server. createobject method. Server. Createobject can create an object immediately. If you no longer use this object, you will waste resources. The <Object ID = objname> flag declares the objname. However, no objname is created before its method or attribute is used for the first time.

This is another example of inert computing.

Tip 18: Use typelib statements for ADO and other components

When using ADO, developers often add adovbs.txt to access various constants of ADO. This file must be included on every page where constants are to be used. This constant file is quite large, which adds a lot of system overhead to the Compilation Time and script size of each ASP page.

IIS 5.0 introduces the function of binding to the component type library. This allows you to reference the type library once and use it on each ASP page. Each page does not incur the overhead of compiling constant files, and component developers do not have to create VBScript # _ include files for use on ASP.

To access ADO typelib, place the following statement in global. Asa.

<! -- Metadata name =? Microsoft ActiveX Data Objects 2.5 library?
Type =? Typelib? UUID =? {00000205-0000-0010-8000-00aa006d2ea4 }? -->

Or

<! -- Metadata type =? Typelib?
File =? C: \ Program Files \ common files \ System \ ADO \ msado15.dll? -->

Tip 19: Use the browser verification function

Today's browsers support some advanced functions such as XML, DHTML, Java applets, and Remote Data Services. Use these functions whenever possible. All of these technologies can perform client-side verification and data caching, eliminating the need for a round-trip to the web server. If you are running a smart browser, the browser can perform some verification for you (for example, check whether the credit card verification is valid before executing the post ). Use this function whenever possible. By reducing the round-trip between the client and server, the load on the Web server can be reduced and network traffic can be reduced (although the first page sent to the browser may be relatively large) and any backend resources accessed by the server. In addition, users do not have to read New pages as they normally do, so they feel better. This does not mean that you do not perform server-side verification-you should always perform server-side verification. This prevents clients from generating incorrect data for some reason (such as hackers or browsers that do not run client-side verification routines.

People have already done a lot of work to develop html "independent from browsers. Due to this concern, developers are reluctant to use popular browser features, but these features can improve performance. For some real high-performance websites, you must pay attention to the browser's "access" issue. A good strategy is to optimize the page and adapt it to popular browsers. Using the browser function component, you can easily detect the browser function in ASP. Microsoft FrontPage and other tools help design code suitable for browsers and specified HTML versions. See when is better worse? Weighing the technology trade-offs for further discussion.

Tip 20: Avoid using String concatenation in loop statements

Many people create a string in the loop statement, as shown below:

S =? <Table>? & Vbcrlf
For each errors in RS. Fields
S = S &? <TH>? & Region. Name &? </Th>?
Next

While not Rs. EOF
S = S & vbcrlf &? <Tr>?
For each errors in RS. Fields
S = S &? <TD>? & Variable. Value &? </TD>?
Next
S = S &? </Tr>?
Rs. movenext
Wend

S = S & vbcrlf &? </Table>? & Vbcrlf
Response. Write s

This method may cause some problems. The first problem is that it takes two powers to repeatedly concatenate a string. More broadly, the time spent running this loop statement is proportional to the square of the number of records multiplied by the number of fields. A simpler example can be used to illustrate this problem more clearly.

S = ??
For I = ASC (? A ?) To ASC (? Z ?)
S = S & CHR (I)
Next

In the first iteration, Have you obtained a character string? A ?. In the second iteration, VBScript must re-allocate the string and assign two characters (? AB ?) Copy to S. In the third iteration, it must re-allocate S and copy the three characters to S. In N (26th) iterations, it must be reassigned and n characters must be copied to S. In total, it is 1 + 2 + 3 +... + N, that is, N * (n + 1)/2 copies.

In the above record set example, if there are 100 records and 5 fields, the inner loop will be executed 100*5 = 500 times, the time spent on all replication and reallocation is proportional to 500*500 = 250,000. There are too many replication operations for medium-size record sets.

In this example, the code can be improved by replacing String concatenation with response. Write () or embedded script (<% = response. Value %>. If the response buffer is enabled (it should be), this will be faster, because response. Write only attaches data to the end of the Response Buffer. It does not involve reallocation, so it is very efficient.

If you want to convert an ADO record set to an HTML table, use getrows or getstring.

If you concatenate strings in JScript, we recommend that you use the + = Operator, that is, use S + =? A string ?, Instead of using S = S +? A string ?.

Tip 21: Enable browser and proxy caching

By default, ASP prohibits caching in browsers and proxies. This makes sense, because in essence ASP pages are dynamic with potential information that changes over time. If the page does not require refreshing on each view, you should enable the browser and proxy cache. This allows the browser and proxy to use the cached copy of the page within a certain period of time, you can control the length of time. The cache can greatly reduce the load on the server and shorten the waiting time.

Which dynamic page can be used as the page to be cached? The following are some examples:

The weather forecast page, on which the weather forecast is updated every 5 minutes.
Lists the homepage of news entries or press releases, which are updated twice a day.
Common Fund Performance list, in which basic statistics are updated every several hours.
Note: When the browser or proxy cache is used, the number of accesses recorded on the Web server is reduced. If you want to accurately measure all page views or post announcements, you do not want to use a browser or proxy cache.

Browser cache is controlled by the HTTP "Expiration" header, which is sent to the browser by the Web server. ASP provides two simple mechanisms for sending this header. To set how many minutes after the page expires, set the response. expires attribute. The following example shows that the browser content expires in 10 minutes:

<% Response. expires = 10%>

If response. expires is set to negative or 0, the cache is disabled. Make sure to use a large negative number, such as-1000 (slightly more than one day), to avoid mismatch between the server and the browser clock. The second property response. expiresabsolute will enable you to set the specific time when the content expires:

<% Response. expiresabsolute = # May 31,2001 13:30:15 # %>

Instead of using the response object to set the expiration time, you can write the <meta> MARK into HTML, which is usually written in the

& Lt; Meta HTTP-EQUIV =? Expires? Value =? May 13:30:15?>

Finally, you can use the response. cachecontrol attribute to indicate whether the content can be cached by the HTTP proxy. If this attribute is set to "public", the proxy can cache this content.

<% Response. cachecontrol =? Public? %>

By default, this attribute is set to "private ". Note: proxy caching should not be enabled for pages that display user-specific data, because the proxy may provide users with pages belonging to other users.

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.