ASP coding optimization skills 8

Source: Internet
Author: User

1. Declare VBScript Variables

In ASP, VBScript provides strong support and can seamlessly integrate VBScript functions and methods, which greatly facilitates the extension of existing ASP functions. Because ASP has blurred the concept of variable types, many programmers are also accustomed to not declaring VBScript variables during ASP-VBScript interaction, this increases the server's parsing burden and affects the server's Response Request speed.
In view of this, we can force users to declare variables in VBScript just like forcing users to declare variables in VB. The implementation method is as follows:
Place <% option explicit %> at the beginning of the ASP program line.

2. encode the URL

When we use ASP to dynamically generate a URL address with parameters and perform redirection, the resolution in IE is normal, but the following error occurs during NetScrape browsing:
HTTP Error 400
400 Bad Request
Due to malformed syntax, the request cocould not be understood by the server.
The client shocould not repeat the request without modifications.
The solution is to use the URLencode method of the ASP built-in server Object to encode the generated URL parameters. The example is as follows:
<%
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. Clear objects

After an object is used, the Close method is used to release the system resources occupied by the object, and the object value is set to "nothing" to release the memory occupied by the object. The following code creates a drop-down list using the database content. The sample code 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 rstemp1_conntemp.exe cute (mySQL)
If rstemp. eof then
Response. write "the 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 a string to create an SQL query

Using strings to create a query does not speed up the server's resolution. On the contrary, it increases the server's resolution time. However, we recommend that you use strings instead of simple query statements for queries. The advantage of doing so is that you can quickly discover the program problems and generate programs conveniently and efficiently. Example:
<% MySQL = "" select *"
MySQL = mySQL & "from publishers"
MySQL = mySQL & "where state = 'ny '"
Response. write mySQL
Set rstemp1_conntemp.exe cute (mySQL)
Rstemp. close
Set rstemp = nothing
%>

5. Use case to select Conditions

When selecting conditions, use case statements whenever possible to avoid using if statements. By using case statements, the program can be streamlined and executed faster than if statements. Example:
<%
FOR 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, "11") THEN
Num = num & "th"
ELSE
Num = num & "st"
END IF
CASE "2"
IF InStr (num, "12") THEN
Num = num & "th"
ELSE
Num = num & "nd"
END IF
CASE "3"
IF InStr (num, "13") 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. Use the constant defined in the adovbs. inc file to open the record set

When opening a record set, you can define the type of the cursor and lock that the record set opens. Some constants are defined in the adovbs. inc file to define these types. The adovbs. inc file is saved in the \ inetpub \ iissamples \ IISamples directory. The following lists several common cursor types and lock types.
Cursor type: The adOpenFowardOnly cursor can only be forward. The adOpenKeyset cursor can be forward or backward. If a user adds a record, the new record will not appear in the record set. The adOpenDynamic cursor is dynamic and random; the adOpenStatic record set does not reflect any changes made to other users.
Lock type: adLockReadOney cannot modify records in the record set; adLockPessimistic locks a record when editing it; adLockOptimstic locks a record when calling the record set 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 defining objects in the global. asa file.

Because the content in the global. asa file can be referenced by all files in the site, object definition in the global. asa file can save a lot of repetitive work. For example, define the following definition in the application_onstart function of global. asa:
<% SUB application_onstart
Set application ("theCONN") = server. createobject ("adodb. connection ")
End sub %>;
In this way, similar references can be made in any code of the site:
<%
MySQL = "select * from publishers where state = 'xur'
Set rstemp = application ("theconn" cmd.exe cute (mySQL)
%>
Similarly, you can create a record set object in the session_onstart function.
<% SUB session_onstart
Set session ("rstemp") = server. createobject ("adodb. recordset ")
End sub %>
Then make the following reference on the site:
<%
MySQL = "select * from publishers where state = 'xur'
Set session ("rstemp" zookeeper conntemp.exe cute (mySQL)
%>
However, this operation also has a huge negative impact. Because both Application and Session variables release the resources occupied only when the website is closed, therefore, Session parameters waste a lot of unnecessary memory, and the Application variable becomes the bottleneck of server performance.
Solution: Create an ASP page for defining objects and introduce this ASP page on the page for calling these objects. If the ASP page name of the defined object is define. asp, you only need to add the following statement to the corresponding ASP page to introduce the page.
<! -- # Include virtual = "/define. asp" -->
When introducing pages, it is best not to include the <% @ LANGUAGE = "VBSCRIPT" %> statement in the ASP file to be introduced. In the ASP file, only one script parsing language defined by @ is allowed.

8. Security Protection

ASP provides a good code protection mechanism. All ASP code is executed on the server and only returned to the client for code execution. Even so, in earlier versions of IIS, you can add: $ DATA after the file name to view ASP source code. This is beyond the scope of Web Server security. Below are two simple security considerations.
Although it is recommended to introduce a file using inc as the extension in ASP, it is recommended to use ASP as the extension of the cited file here. When these codes run on a Web Server with poor security mechanisms, you only need to enter the address of the introduced file (inc is the extension) in the address bar to view the content of the introduced file, this is because on the Web Server, if the dynamic Connection Library of a certain type (such as inc) is not defined, the file is displayed as source code.
Do not place database files inside the website structure. In this way, when attackers obtain the database path, they can easily obtain the database and modify the database content. A good practice is to create a DSN (Date Source Name) for the database and directly access the DSN during database access.

Five ASP Acceleration Techniques

Tip 1: Improve the efficiency of using the Request set
Accessing an ASP set to extract a value is a time-consuming and computing resource-consuming process. This operation contains a series of searches for related sets, which is much slower than accessing a local variable. Therefore, if you want to use a value in the Request set multiple times on the page, you should consider storing it as a local variable. For example, you can write the code below to speed up the processing of the script engine:
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 2: directly access the appropriate set
If there is no choice, otherwise do not use strPage = Request ("page") to obtain parameters, because this will search all the sets in order-QueryString, Form, Cookies, ClientCertificate, and ServerVarible until the name of the first matching value is found. This is less efficient and insecure than directly accessing an appropriate set, unless it is absolutely guaranteed that this value will not appear in another set.
For example, you may want to search for the name of the WEB server that meets the customer's Request, which is achieved by searching for "SERVER_NAME" in the Request. ServerVarables set in each query. However, if other sets also contain values named "SERVER_NAME" (key names are case-insensitive), an error is returned when Request ("server_Name") is used. All in all, access the appropriate set as directly as possible.

Tip 3: Use the Response. IsClientConnected Attribute before time-consuming operations
Using Response. IsClientConnected is a useful way to check whether the user is still connected to the server and loading the web page created by ASP. If you disconnect or stop downloading, you do not need to waste resources on the server to create a webpage, because the buffer content is discarded by IIS. Therefore, for web pages that require a large amount of time computing or resource usage, it is worth checking whether the viewers are offline at each stage:
...... Code to create first part of the page
If Response. IsClientConnected Then
Response. Flush
Else
Response. End
End If
...... Code to create next part of page

Tip 4: optimize ADO operations in ASP
Generally, data constitutes the actual content of a WEB site. Therefore, it is very useful to optimize ADO operations to accelerate ASP code execution:
A. SELECT only the required columns: When opening the ADO record set, the table name (SELECT *) should not be used automatically unless all columns are obtained *). Using a separate column means reducing the amount of data sent to or from the server. Even if you need to use all columns, naming each column independently will achieve the best performance, because the server no longer needs to explain the names of these columns.
B. Use stored procedures as much as possible. Stored procedures are pre-compiled programs that contain a prepared execution plan, so they are faster than SQL statements.
C. Use the appropriate cursor and lock mode. If all the work is to read data from the record set and display it on the screen, the default record set can only be moved forward and read-only. The less detailed ADO is to maintain records and locks, the higher the execution performance.
D. Use object variables. When traversing a record set, one way to improve performance is to use object variables to point to Members in the set. For example:
While Not RsGc. EOF
Response. Write "Project name:" & RsGc ("GcMC") & "(project code:" & RsGc ("GcCode ")&")
"
RsGc. MoveNext
Wend
You can rewrite the following code 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 creates an object variable reference, so you can use the object variable instead of the actual variable, which means that the script engine is less effort, because the number of indexes in the set is reduced.

Tip 5: Do not mix script Engines

We know that you can use VBScript or JScript on the ASP page. However, JScript and VBScript cannot be used on the same page at the same time. Because the server must instantiate and try to cache two (rather than one) script engines, which increases the burden on the system to a certain extent. Therefore, in terms of performance, you should not mix multiple script 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.