ASP Coding Optimization Technique 8 _asp Foundation

Source: Internet
Author: User
Tags case statement dsn urlencode
1. Declaring VBScript variables

In ASP, there is strong support for VBScript, the ability to seamlessly integrate VBScript functions, methods, so as to extend the existing functionality of the ASP to provide a great convenience. Since the concept of variable types has been blurred in ASP, many programmers are wont to declare VBScript variables in the process of interacting with VBScript, thus aggravating the resolution burden of the server and affecting the response request speed of the server.
For this reason, we can force a user to declare a variable in VBScript just as a variable declaration is enforced in VB. The implementation method is:
Place <% option explicit%> at the beginning of the ASP program.

2. Encode the URL address

In our use of ASP dynamically generated with a parameter URL address and jump, in IE parsing is normal, but in the Netscrape browsing there are errors as follows:
HTTP Error 400
Bad Request
Due to malformed syntax, the request could not being understood by the server.
The client should not repeat the request without modifications.
The workaround is to URL-encode the generated URL parameters using the UrlEncode method of the ASP built-in server object, as shown in the following example:
<%
Url= "Xur.asp"
Var1= "username=" & Server. UrlEncode ("Xur")
Var2= "&company=" & Server. UrlEncode ("Xurstudio")
Var3= "&phone=" & Server. UrlEncode ("021-53854336-186")
Response.Redirect URL & "?" & Var1 & var2 & VAR3
%>

3. Empty Objects

When you finish working with the object, you first use the Close method to release the system resources occupied by the object, and then set the object value to "nothing" to free the object from memory. The following code uses the database content to create a drop-down list. The code example is as follows:
<% mydsn= "Dsn=xur;uid=xur;pwd=xur"
Mysql= "SELECT * from authors where au_id<100"
Set Conntemp=server.createobject ("Adodb.connection")
Conntemp.open MyDSN
Set Rstemp=conntemp.execute (MySQL)
If Rstemp.eof Then
Response.Write "Database is empty"
Response.Write MySQL
Conntemp.close
Set conntemp=nothing
Response.End
End If%>
<%do until Rstemp.eof%>
<%
Rstemp.movenext
Loop
Rstemp.close
Set rstemp=nothing
Conntemp.close
Set conntemp=nothing
%>

4. Use string to establish SQL query

Using a string to establish a query does not speed up the resolution of the server, and, conversely, it increases the resolution time of the server. However, it is still recommended that you use strings instead of simple query statements to query. The advantage of doing this is that you can quickly discover where your program problems are, thus facilitating the efficient generation of programs. Examples are as follows:
<%mysql= "" SELECT * "
Mysql= MySQL & "From publishers"
Mysql= MySQL & "where state= ' NY"
Response.Write MySQL
Set Rstemp=conntemp.execute (MySQL)
Rstemp.close
Set rstemp=nothing
%>

5. Use case for conditional selection

When making a conditional selection, use the case statement as much as possible, avoiding the use of the IF statement. With case statements, you can process the program and execute it faster than if statements. Examples are as follows:
<%
For i = 1 to 1000
n = i
Response.Write Addsuffix (N) & "<br>"
NEXT
%>
<%
Function Addsuffix (num)
Numpart = Right (num,1)
SELECT Case Numpart
Case "1"
IF InStr (num, "one") THEN
num = num & "th"
ELSE
num = num & "St"
End IF
Case "2"
IF InStr (num, "a") THEN
num = num & "th"
ELSE
num = num & "nd"
End IF
Case "3"
IF InStr (num, "THEN")
num = num & "th"
ELSE
num = num & "rd"
End IF
Case "4"
num = num & "th"
Case ELSE
num = num & "th"
End SELECT
Addsuffix = num
End FUNCTION
%>

6. Open a Recordset using constants defined in the Adovbs.inc file

When you open a recordset, you can define the cursor type and lock type that the recordset opens. Some constants are defined in the Adovbs.inc file to define these types. The Adovbs.inc file is saved under the \inetpub\iissamples\iisamples directory. Several commonly used cursor types and locking types are listed below.
Cursor Type: Adopenfowardonly cursors can only forward, adOpenKeyset cursors can be forward or backward, and a new record will not appear in a recordset if the user adds a record; adopendynamic cursor dynamic The adOpenStatic recordset does not reflect changes to records caused by other users.
Lock type: Adlockreadoney cannot modify records in a recordset; adLockPessimistic locks a record when it is edited; locks a record when Adlockoptimstic calls the recordset Update method ; Adlockbatchopeimstic records can only be updated in batches.
<!--#INCLUDE virtual= "/adovbs. INC "-->
<%
Connectme= "Dsn=xur;uid=xur;pwd=xur"
Sqltemp= "SELECT * From Publishers where name= ' Xur '"
Set Rstemp=server.createobject ("ADODB. Recordset ")
Rstemp.open sqltemp, Connectme, adopenstatic,adlockoptimstic
Response.Write Rstemp.recordcount & "Records in<br>" & Sqltemp
Rstemp.close
Set rstemp=nothing
%>

7. Avoid object definitions in the use of global.asa files

Because the contents of the Global.asa file can be referenced for all the files in the site, there is no doubt that the object definition in the Global.asa file can save a lot of duplication of effort. For example, in the Application_OnStart function in Global.asa, define the following:
<%sub Application_OnStart
Set Application ("Theconn") =server.createobject ("ADODB. Connection ")
End SUB%>;
This allows you to make similar references in any site code:
<%
Mysql= "SELECT * From Publishers where state= ' Xur '
Set Rstemp=application ("Theconn"). Execute (MySQL)
%>
Similarly, you can create a Recordset object in the Session_OnStart function
<%sub Session_OnStart
Set session ("Rstemp") =server.createobject ("Adodb.recordset")
End SUB%>
Then make the following reference in the site also:
<%
Mysql= "SELECT * From Publishers where state= ' Xur '
Set session ("Rstemp") =conntemp.execute (MySQL)
%>
But this also has a great negative impact, because application and session variables are only when the site is closed to release the resources occupied, so session parameters will waste a lot of unnecessary memory, and at this time application variable become server performance bottleneck.
Workaround: Create an ASP page for the definition object, and introduce the ASP page on the page where you need to invoke these objects. Assuming that the ASP page name of the defined object is define.asp, the page can be introduced as long as the following statement is added to the corresponding ASP page.
<!--#INCLUDE virtual= "/define.asp"-->
When introducing a page, it is best to not include <% @LANGUAGE = "VBSCRIPT"%> statements in the ASP file to be introduced. Because in an ASP file, there can be only one sentence parsing language defined by @.

8. Safety Protection

ASP provides a good code protection mechanism in which all ASP code is executed on the server side and returned only to client code execution results. Even so, in older versions of IIS you can add:: $DATA to view the source code of the ASP, which is already in the Web server security category and is not covered in this article. Here are two simple security considerations.
Although it is recommended in ASP to introduce files to Inc as an extension, the ASP is still recommended as the extension of the primer file. When this code is running on a poorly secured Web server, you can browse the contents of the introduced file by simply entering the address of the address bar that introduces the file (inc), because on the Web server, if you do not have a dynamic connection library defined to resolve a type, such as Inc, The file is displayed in Source mode.
Do not put database files inside the structure of the site, so that when the malicious person to obtain the database path, you can easily access the database, and then arbitrarily change the database content. It is a good practice to establish a DSN (Date Source Name) for the database and access the DSN directly when making database access.


five techniques for raising speed of ASP

One technique: improving the efficiency of using the request collection
Accessing an ASP collection to extract a value is a time-consuming process that takes up computational resources. Because this operation contains a series of searches for the related set, this is much slower than accessing a local variable. Therefore, if you intend to use a value in the request collection more than once in a page, you should consider storing it as a local variable. For example, write your code in the following form to speed up script engine processing:
Strtitle=request.form ("Title")
Strfirstname=request.form ("FirstName")
Strlastname=request.form ("LastName")
If Len (strtitle) Then Strtitle=strtitle & ""
If strfirstname= "" Then Strfullname=strtitle & "" & strLastName
Elseif Len (strfirstname) =1 Then
Strfullname=strtitle & strFirstName & "." & strLastName
Else
Strfullname=strtitle & strFirstName & "" & strLastName
End If

tip Two: Direct access to the appropriate set
If you don't have a choice, do not use the form of strpage=request ("page") to get the arguments, as this will search all collections in order-querystring, Form, Cookies, ClientCertificate, Servervarible until the name of the first matching value is found. This is less efficient than direct access to the appropriate set, and is unsafe unless it is absolutely guaranteed that the value does not appear in another set.
For example, you might want to search for a Web server name that satisfies a customer request, which is done by looking for "server_name" in the Request.servervarables collection in each query. However, if the other collection also contains a value named "SERVER_NAME" (the key name is case-insensitive), you will get the wrong result when you use Request ("SERVER_NAME"). In summary, you should access the appropriate collection as direct as possible.

Tip Three: Use the Response.IsClientConnected property before a time-consuming operation
Using response.isclientconnected is a useful way to observe whether a user is still connected to the server and is loading the Web page created by ASP. If the user disconnects or stops downloading, we don't have to waste the server's resources creating the page because the buffer content will be discarded by IIS. Therefore, for those pages that require a lot of time to compute or use more resources, it is worth checking that the viewers are offline at each stage:
...... Code to create the page
If response.isclientconnected Then
Response.Flush
Else
Response.End
End If
...... Code to create next part of page

tip four: Optimizing ADO operations in ASP
Generally speaking, the data constitutes the actual content of the Web site. Therefore, it is useful to optimize ADO operations to speed up ASP code execution:
A. Select only the columns you want: When you open an ADO recordset, you should not automatically use the table name (that is, select *) unless you need to get all the columns. Using a separate column means that the amount of data sent to or removed from the server will be reduced. Even if you need to use all the columns, it is best to name each column individually, because the server does not have to explain the names of these columns.
B. Use stored procedures as much as possible. A stored procedure is a precompiled program that contains a prepared execution plan, so it executes faster than the SQL statement.
C. Use the appropriate cursor and lock mode. If all you do is read data from the recordset and display it on the screen, use the default only forward, read-only recordset. The less work ADO uses to maintain the details of records and locks, the higher the performance of the execution.
D. Use object variables. One way to definitely raise performance when traversing a recordset is to use object variables to point to members in the collection. For example:
While not rsgc.eof
Response.Write "Project name:" & RSGC ("GCMC") & "(Engineering Code:" & RSGC ("Gccode") & ")
"
Rsgc.movenext
Wend
You can use the code rewritten as follows to speed up execution:
Set GCMC=RSGC ("GCMC")
Set GCCODE=RSGC ("Gccode")
While not rsgc.eof Response.Write "project name: & GCMC &" (Project Code: "& Gccode &")
"Rsgc.movenext
Wend

The new Code establishes a reference to an object variable, so you can use object variables instead of actual variables, which means that the script engine has less work because the number of indexes in the collection has become smaller.

Tip Five: Don't mix script engines

We know that you can use either VBScript or JScript in an ASP page. However, it is not advisable to use both JScript and VBScript on the same page. Because the server must instantiate and attempt to cache two (rather than one) scripting engines, this increases the system burden to some extent. Therefore, for performance reasons, you should not mix multiple scripting engines on the same page.
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.