22 Tips for improving ASP performance (ii)

Source: Internet
Author: User
Tags array arrays expression flush object model variables variable access
Skills | performance

  tip 12: Copy common data into a script variable

When accessing COM objects in ASP, you should copy common object data into script variables. Will reduce COM method calls. The COM method invocation cost is relatively higher than the access script data. When accessing collection and
When Dictonary objects, this technology can also reduce the high cost of querying.

Typically, when you're ready to access an object's data more than once, you should put that data in a script object.

The main goal of this optimization is to request variables (form and querystring variables). For example, your site passes a querystring variable called UserID, which is assumed to be referenced 10 times on a particular page userid. At the top of the ASP page, assign the UserID value to a variable to replace the 10 call request
("UserID") that will deliver 9 COM calls.

In practice, the expensive cost of accessing COM properties or methods may be more subtle. Here's an example that shows a normal code:

Foo.bar.blah.baz = Foo.bar.blah.qaz (1)
If Foo.bar.blah.zaq = Foo.bar.blah.abc Then ' ...

Here's how to run this code:

1. variable foo is resolved to a global object
2. The variable bar is resolved to a member of Foo. This triggers a COM method call once
3. The variable blash is resolved as a member of the Foo.bar. Again, this triggers a COM method call once
4. The variable Qaz is resolved as a member of the Foo.bar.blash. Yes, this also triggers a COM method call once
5. Call Foo.bar.blah.qaz (1). One or more COM method calls. Get a picture?
6. Repeat steps 1 through steps 3来 parse Baz. The system does not know if calling Qaz will change the object model, so steps 1 through 3 are executed again to parse the Baz
7. Parse out Baz is a member of the Foo.bar.blah, execute attribute put.
8. Repeat steps 1 through steps 3来 parsing Zaq
9. Repeat steps 1 through steps 3来 parsing ABC

As you can see, this is how inefficient (and wait). The quick way to do this is to write VBScript in the following code:

Set myobj = Foo.bar.blah ' Do the resolution of blah ONCE
Myobj.baz = Myobj.qaz (1)
If Myobj.zaq = Myobj.abc Then ' ...

If you are using VBScript 5.0 or later, you can use the WITH statement:

With Foo.bar.blah
. Baz =. Qaz (1)
If. Zaq =. ABC Then ' ...
...
End With

  Tip 13: Avoid using variable arrays

Try to avoid using variable arrays. Now that you're concerned about performance, it's best to set the maximum size it can be when the array is initialized. Of course, this is not to say you know that you don't need a few m of memory, but you should still allocate so much to the array.

The following code is a demonstration of irrational use of ReDim:

<%
Dim MyArray ()
Redim MyArray (2)
MyArray (0) = "Hello"
MyArray (1) = "Good-bye"
MyArray (2) = "Farewell"
...
Redim Preserve myarray (5)
MyArray (3) = "More Stuff"
MyArray (4) = "Even more stuff"
MyArray (5) = "yet more Stuff"
%>

The simple initialization of an array is defined as the correct size (this should be 5) far better than the ReDim array. You may waste some memory (if you end up not using all of the elements), but get the speed!

  Tip 14: Use response buffering (Response buffering)

Turn on response buffering to buffer the output of the entire page, which reduces the number of times you write to the browser and improves overall performance. It takes time and resources to write a browser every time, so reducing the number of browsers can improve performance, while TCP/IP protocols send less chunks of data more efficiently than sending smaller chunks of data.

There are two ways to turn on response buffering. First, you can use Internet Service Manager to turn on the response buffer for the entire application. This is the recommended method. In IIS 4.0 and IIS 5.0, when you create a new application, the response buffering is turned on by default. The second approach: for each stand-alone ASP page, you can open the response buffer by placing the following code at the top of the page:

<% Response.Buffer = True%>

This line statement must be executed before all buffered data is written (that is, before all HTML and the cookie is set through Response.Cookies). Typically, it's best to turn on the response buffer for the entire application, so you don't have to write the above statement at the top of each ASP page.

Response.Flush

For response buffering, because users have to wait for the entire page to build before they see something, users can sense that the ASP page response is slow (although the overall response time is shortened), and you can Response.Buffer = False to turn off response buffering for a page that is running longer. , but a better strategy is to use the Reponse.flush method. This method prints all HTML that has been generated by ASP to the browser. For example, a large table of 1,000 rows, after writing 100 lines, the ASP can invoke Response.Flush to force the result to be written to the browser, so that the user can see 100 rows of data before the rest of the rows are generated. This technique gives you the most of both worlds-response buffering and progressive data representation in the browser.

(Note that in the example of the 1,000-row table above, many browsers may not draw the entire table before encountering the </table> tag.) If you want your browser to gradually display data, you can divide a large table into smaller tables, and then call Response.Flush for each of the small tables. The new version of IE displays the table before downloading the full table, and displays faster if you specify a column width for the table. )

In addition, when a very large page is generated, response buffering may consume a lot of server memory. This problem can also be solved by using Response.Flush.

  Tip 15: Scripting Chunks and Response.Write statements

VBScript syntax <% = Expression%> writes the value of an expression to the ASP output stream, but if the response buffer is not open, each such statement will want the browser to write the data, and the network stream into a lot of small packets. It will be slow. Similarly, sporadic snippets of script and HTML lead to frequent switching between scripting engines and HTML, reducing performance. Therefore, you should use the following tips: Change a small block of inline expression to call Response.Write. For example, in the following example, each field in each row writes data to the response stream, and each row is toggled in VBScript and HTML:

<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>

The following are more efficient code that is written only once per line to the response stream. All the code is contained in a VBScript block:

<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>

This technique is not effective when response buffering is blocked. It is best to turn on the response buffer and then look at the performance improvement of the bulk Response.Write.

  tip 16: Use resonse.isclientconnected before entering a long time operation

If the user is impatient, they may leave the page before the ASP page calculates their request. If they click on a refresh or jump to another page on the server, the new request will be at the end of the ASP request queue, while the interrupted request is in the middle of the request queue; Typically the server can occur in high load situations (the server has a long request queue and a lot of requests) , which in turn makes the server's load situation even worse. If the user has disconnected, there is no need to execute this ASP page (especially if this is a slow, resource-intensive page) The Response.IsClientConnected property can check this out, and if the property returns false, it should call Resonse.end to end the remaining pages. In fact, IIS 5.0 makes this check rule-whenever an ASP is ready to execute a new request, he checks to see how long the request queue is, and if the queue has more than 3 seconds, the ASP checks to see if the client is connected, and if the client is disconnected, the ASP terminates the request immediately. You can use the AspQueueConnectionTestTime setting to adjust the timeout of 3 seconds.

If you have a very time-consuming page to perform, you can also check in the page
Response.IsClientConnected. When the response buffer is open, use in the page run
Response.Flush can also give users the feeling of being executed.

Note: On IIS 4.0, the response.isclientconnected result may be incorrect unless you perform the Response.Write first, and Response.Flush must be executed first if the response buffer is already open. On IIS 5.0, there is no such need, and response.isclientconnected is working properly. In any case, response.isclientconnected always consumes some time, so it should only be performed in a page that takes at least 500ms of execution. The first principle is not to call this property repeatedly in a tight loop.

  Tip 17: Instantiate objects with <OBJECT> tags

If you want to refer to an object in Global.asa that is not used in all code paths (a particular server-or application-scope object), use <object runat=server id=objname> Tag definitions are more appropriate than the Server.CreateObject method definition. Because Server.CreateObject immediately creates an object, it wastes resources if you do not use this object later. <object id=objname> only declares objname, but objname is not really created; objname is created the first time it is used.

  tip 18: Use type library declarations for ADO and other components

When using ADO, developers often access ADO constants by including Adovbs.txt. This file must be included in every page that uses constants, and the constant file is quite large enough to increase the amount of time and resources spent processing each page.


IIS 5.0 introduces the ability to bind component type libraries, allowing only the type library to be referenced once, and then being used in each ASP page. Each page does not consume resources for compiling constant files; The component developer does not have to prepare VBScript inclusion files for the ASP.

You can access the ADO type library by placing 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: Avoid string concatenation in loops

Many people like to use the following loop to generate a string:

s = "<table>" & VbCrLf
For each fld in Rs. Fields
s = S & "<th>" & fld. Name & "</th>"
Next

While not Rs. Eof
s = S & vbCrLf & "<tr>"
For each fld in Rs. Fields
s = S & "<td>" & Fld.value & "</td>"
Next
s = S & "</tr>"
Rs. MoveNext
Wend

s = S & vbCrLf & "</table>" & VbCrLf
Response.Write S

There are some problems with this approach. The first is that connecting strings in a loop causes the time to grow two times (quadratic), or that the time to run this cycle is proportional to the square of the number of fields in the record.

The following simple example can see the essence more clearly:

s = ""
For i = ASC ("A") to ASC ("Z")
s = S & Chr (i)
Next

In the first cycle, S equals "A"; in the second cycle, VBScript must redistribute the space of S and assign the string "AB" to s; in the third cycle, redistribute the space of S, and reassign the value. In the nth (26) cycle, VBScript redistributed and copied the n-times string to s, so that the total is 1+2+3+...+n=n* (n+1)/2 copies.

In the example above, if there are 100 records, each record has 5 fields, then the internal loop executes 100*5=500 times, all the number of copies and reallocation of space corresponding to the 500*500=250,000 times; This is only for a very small recordset.

In this case, you can improve performance by replacing string concatenation with Response.Write or inline scripts (<% = Fld.value%>). If the response buffer is (and should be) turned on, Response.Write simply adds data to the end of the response buffer, does not reallocate memory, and is therefore highly efficient.

You can consider using the GetRows or GetString functions in situations where you are specifically converting an ADO recordset to an HTML table.

If you use the JScript connection string, the + = operator is strongly recommended; that is, use s = = "Some string", do not use s = S + "some string".

  Tip 20: Use Server.Transfer instead of Response.Redirect

Response.Redirect tells the browser to request another page. This function is often used to jump the user to the login or error page. Now that redirect forces a new page request, the result is two interactions between the browser and the Web server, and the Web server has to handle an extra request more than once. IIS 5.0 introduces a new function: Server.Transfer This function directly to another page on the same server, avoiding additional browser to Web server interaction and improving performance.

  Tip 21: Add a slash (/) to the end of the directory URL

If the trailing slash is omitted, the browser sends a request to the server and is told that its request is a directory; then the browser sends another two requests, but this time the URL is preceded by a slash, and the server responds to the browser again. If you add a slash to the URL at the beginning, you can save unwanted requests; Of course, for the sake of user-friendliness, you can omit the trailing slash when displaying the name.

For example, follow the following:

<a href=http://www.webjx.com/;; title= "webjx.com" >http://www.webjx.com<; A>

  tip 22: Avoid using server-side variables

Accessing server-side variables will cause the site to send a special request to the server to collect all server-side variables, not just the one you visit.



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.