ASP quick execution of dynamic web pages

Source: Internet
Author: User
Tags array definition dsn http cookie

This is a detailed article on how to streamline code and Asp features for the fastest execution speed. For a dry user, any latency between pressing the user button and the result on their screen may mean that they will go to another site? If you are a commercial site, this may mean losing potential sales.
We have no way to control the user's bandwidth, but we can indeed achieve the best * by optimizing the Asp site. Most of the potential * improvement is through system change rather than code tightening. an inappropriate idea is to ask the system ** to upgrade the system once it encounters a system efficiency problem.
First, which of the following factors may affect Asp? Unfortunately, there are many factors? The following are only part of the list:
Available Bandwidth
Server processor and other hardware speed
Other programs running on the server (such as those OpenGL screen saver !)
Database connection mode, connection pool, and database system (for example, Oracle is better than SQL Server and SQL server is better than Access)
Language used
Stored procedures are superior to row-based SQL statements
Good Asp programming experience, such as error handling, using compiled components instead of VB or JavaScript.
Some of the above factors may have been noticed by developers with IIS knowledge and experience, but other factors may be very complicated for them. In this article, I will try to explain all the factors that affect Asp *'s performance. Let's take a look at the main things we can do within milliseconds of shaving.
ASP script size
Is it longer than the required length when you use a webpage (or other pages? This is something Asp * can be reduced at the beginning of execution. ASP scripts are useful when used to obtain information and format output, but they are also interpreted and executed line by line. Therefore, the longer your script is, the longer it will be executed.
If your script is huge, how can we reduce the script length? Here are some suggestions:
You can convert them into server-side components, that is, to convert them into VB dynamic link library DLL or to uncompiled components through advanced Windows programming language or appropriate COM interface language? And register them on the server. The Quick Guide can be found
Http://www.websitesjournal.com/articles/activex_for_asp.html. Compiling a well-written ActiveX component can not only greatly improve *, but also protect your software (scripts ), especially when you publish your Asp site on a third-party host.
Because the script is interpreted and executed line by line, removing unnecessary scripts or creating more efficient scripts can improve. If you have hundreds of lines of code in a single Asp file, you may be able to well classify users, sales, and data services. In fact, if you do this, you may find some redundant code: If you need to output several tables, you can write a common function to output a table, just call it multiple times.
When talking about the Asp script size, you have to mention the file size. When you use an include file, the entire include file is loaded. When the include file is included, it is equivalent to writing the part of code in the Asp file itself. Therefore, if you define many common methods and definitions in a lengthy inclusion file, you must understand that when you include the file, whether you want to use each method or definition, it is fully loaded. ASP caches all the expanded code, which reduces the search efficiency. In this case, the contained files must be split into smaller, modular files. You must also understand that a page request containing a file is regarded as a separate page request by the server. using too many contained files will affect the download time.
<! -- # Include file = "Header. asp" -->
<! -- # Include file = "Footer. asp" -->
<SCRIPT language = "vbscript" runat = "server">
Sub Main ()
WriteHeader
WriteBody
WriteFooter
End Sub
Sub WriteBody ()
...
End Sub
Main? 'Calling Process Main
</SCRIPT>
If your script is lengthy, use Response. IsClientConnected. This means that when the client is no longer connected to the server, your server CPU can avoid cyclic waiting.
<%
'Check whether the client is still connected
If Not Response. IsClientConnected Then
'Still connected, Handler
Else
'Disconnected
End If
%>
Interspersing ASP and HTML
Does everyone do this? When outputting a table, we convert it between ASP and HTML code, which is a bad habit. For example:
<HTML>
<BODY>
<%
Set MyConn = Server. CreateObject ("ADODB. Connection ")
MdbFilePath = Server. MapPath ("sample. mdb ")
MyConn. Open "Driver = {Microsoft Access Driver (*. mdb)}; DBQ =" & MdbFilePath &";"
SQL _query = "SELECT * FROM Friends"
Set RS = MyConn. Execute (SQL _query)
While not rs. EOF
%>
<LI> <% = RS ("Name") %>: <a href = ""> Homepage </A>
<%
RS. MoveNext
WEND
%>
</BODY>
</HTML>
Another common example is when the IF statement is used:
<%
If Not Session ("DBOpen") Then
%>
<H1> Database not connected </H1>
<%
Else
%>
<H1> Database open </H1>
<%
End If
%>
In these cases, the script * can be improved by writing the server-side script together and using Response. write to generate Html code. For example:
<%
If not Session ("DBOpen") Then
Response. Write "<H1> Database not connected </H1>"
Else
Response. Write "<H1> Database open </H1>"
End If
%>
In the case of large scripts and many scripts, you can see that * can be improved. Note that the <% flag is avoided here, which can improve *. ASP does not need to calculate the Ascii code of characters when executing scripts.
Session Status
In Asp, the ability to maintain a certain State through Session is very powerful. However, it will affect your * capabilities. Obviously, the scalability of your site has become another problem if you restrict the use of sessions. However, sessions consume server resources for each user.
If you do not use the session variable, or do you actually not need to use it? Using a hidden form field to save data in the database, is it a trick to query strings? So you should disable the Session status. You can use the following statement to disable session:
@ EnableSessionState = False
In this way, ASP no longer checks session information.
If you have to rely on the session state, avoid storing a large amount of data in the session object. Sessions in IIS are maintained when the client's HTTP cookie is available. As a result, the session occupied by the session exists and is occupied until the session ends or times out. In this way, if many users use your program at the same time, your server resources may be exhausted.
Database Access
Is database access necessary? Accessing the database will drastically slow down your program, but it is clear that without a database, many sites will become worthless. However, by accessing the database through stored procedures instead of using Embedded SQL statements, you can improve the potential * yes. By using stored procedures and ActiveX Data Objects (ADO), they are also flexible *. Output data from stored procedures as much as possible.
Check that your database has an index, because this can directly improve the efficiency of your program. Similarly, try to run Update Statistics on your database server to help track your data distribution. In this way, your database can modify the query execution based on the information. Note that some databases, such as MS Access, can be accepted in enterprise-level programs? SQL Sever 7.0 or Oracle is a better bet.
Let SQL work as it is designed. It can count, join, sort, and group data. When you can write a query statement to do these things, do not use other languages.
Below is a simple syntax for counting all columns:
SELECT count (*) FROM publishers WHERE state = 'ny'
If you count a specified column, you must use the group by statement to group the column; otherwise, it will not work:
SELECT count (city), city FROM publishers group by city
Data returned by category:
SELECT * FROM TableName WHERE FieldName> 50 OR FieldName <100 order by FieldName2, Field Name3
Use Odbc or file DSN to connect to the database? Use the fast OLEDB Provider technology to connect to your database instead of using the DSN connection. You no longer need to ask your ISP (or database ** staff/Network Administrator) to create a system DSN for you. When you remove Web files, you do not need to change the configuration.
OLEDB is between the ODBC layer and applications. On your ASP page, ADO is located on top of ODEDB ". Your ADO call is first sent to OLEDB and then to ODBC layer. However, you can directly connect to the OLEDB layer, and if you do so, you will be able to see improvements on the server side. However, how to directly connect to OLEDB?
If you use SQLServer 7, use the following connection code to connect to the database:
StrConnString = "DSN =''; DRIVER = {SQL SERVER };"&_
"UID = myuid; PWD = mypwd ;"&_
"DATABASE = MyDb; SERVER = MyServer ;"
The most important parameter is DRIVER =. If you want to bypass ODBC and use OLEDB to connect to SQL Server (this is a faster connection), use the following syntax:
StrConnString = "Provider = SQLOLEDB.1; Password = mypassword ;"&_
"Persist Security Info = True; User ID = myuid ;"&_
"Initial Catalog = mydbname ;"&_
"Data Source = myserver; Connect Timeout = 15"
Is there anything wrong?
Now you may feel a little strange: What are the key points of our new connection method? Why not use the standard DSN-less/System DSN path? Well, according to the test results of Wrox in his book ADO 2.0 Programmer's Reference, if you use the OLEDB connection to compare with the DSN or DSN-less connection method, you will find the following improvements:
* Comparison:
SQL Access
OLEDBDSNOLEDBDSN
Connection time: 18? 82? Connection time: 62? 99
Time for querying 1,000 records: 29005400 time for querying 1,000 records: 100950
Note: This result can be found on pages 2.0 and 232nd of Wrox's book ADO 233 Programmer's Reference. The unit of time is millisecond, and the query time of 1,000 records is calculated by the server-side cursor (when the client-side cursor is used, the * energy of the oledb and The DSN record set is not much different ).
ASP decoding problems:
Try to confirm user input on the client to reduce the number of HTTP back-and-forth requests. If the browser supports JavaScript or other scripts, use their power to release more server resources.
The following VBScript runs in the client browser and is used to verify user information before it is submitted to your server:
<Script language = "VBScript">
<! --
Sub btnEnter_OnClick
Dim TheForm
Set TheForm = Document. MyForm
If IsNumeric (TheForm. Age. Value) Then
TheForm. submit
Else
Msgbox "Please enter a numerical age ."
End if
End Sub
// -->
</SCRIPT>
<Forpolichod = "POST" name = MyFormaction = "myfile. asp">? Name: <INPUT typr = "text" name = "Name">
Age: <INPUT type = "text" name = "Age">
<INPUT type = "button" name = "btnEnter" value = "Enter">
</FORM>
Use local variables to avoid using global variables. Local variables are faster accessed by the Asp script engine than global variables because you do not need to search the entire name field. Avoid changing the array definition. In the first initialization, it is more efficient to allocate enough space. In this case, you may waste some memory, but you get the speed advantage. This technology is obviously effective when the server load is heavy.
If you need to reference objects that are not necessarily used, you 'd better use the <OBJECT> flag instead of the Server. CreateObject method. Using Server. CreateObject causes the OBJECT to be created immediately. Otherwise, the <object> flag does not create the OBJECT immediately. If you do not use this object after using the <OBJECT> definition, you will not waste resources.
For example, the following example uses the <OBJECT> flag to create an application-scope Ad wheel Ad Rotator OBJECT.
Example:
<OBJECT runat = server scope = Application id = MyAds progid = "MSWC. AdRotator">
</OBJECT>
After the Ad Rotator object is stored in the Application, you can use the following syntax to access the object on any program page.
<% = MyAds. GetAdvertisement ("CustomerAds.txt") %>
Turn on the 'option Explicit 'switch. In VB and VBScript, you can use variables without explicit declaration. However, you can use this option to identify and define variables, so that you can write variables well and help improve. An undefined local variable slows down because the namespace must be searched before the variable exists. Get rid of it, so that each variable is clearly defined (first defined and then used ).
This is a good habit. it may trap typos, which is faster.
Unless you really need to use it, do not use the Server. MapPath method. If you know the real path, use the real path. To use MapPath, you need IIS to retrieve the current server path, which means you have to send a special request to the server, which means * yes. Another method is to store the path to a local variable and use it as needed, so that the server does not need to perform multiple searches.
Check how you did it yourself
You can use tools to measure the performance of your system *, such as the System * Performance Monitor, netMon, and PerfMon. WCAT (web Capacity Analysis Tool) can be used to test Web ). With WCAT, you can test your IIS server and network configuration to respond to a variety of customer requests, data, or HTML pages. These test results can be used as guidance for optimizing your server and network configurations. WCAT is designed to estimate the workload of Internet services (or Windows NT) and IIS in Windows 2000.
(Simulation ). For more information, see IIS Resource Kit ). There is also a lengthy WCAT User Guide with a download link in the MSDN online Web sorkshop site. If you take Asp seriously, you must obtain the tool.
Strive to optimize the application *, your web application will run more smoothly. If not, do not affect the server.
Asp implements data paging Using Stored Procedures
I. Create Table tiku_koushi
If exists (select * from dbo. sysobjects where id =
Object_id (n' [dbo]. [tiku_koushi] ') and OBJECTPROPERTY
(Id, N 'isusertable') = 1)
Drop table [dbo]. [tiku_koushi]
GO
Create table [dbo]. [tiku_koushi] (
[Id] [int] IDENTITY (1, 1) not null,
[Title] [varchar] (250) COLLATE
Chinese_PRC_CI_AS NULL,
[List2_id] [char] (10) COLLATE
Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
Ii. Storage Process sp_c
CREATE proc sp_c
@ Tablename varchar (50 ),
@ Title varchar (250 ),
@ List2_id varchar (50)
As
If @ tablename = 'tiku _ koushi'
Select count (*) from tiku_koushi where title like '%' + @ title + '%' and list2_id = @ list2_id
GO
Iii. Storage Procedure sp_search_tiku
Create procedure sp_search_tiku
@ Tablename varchar (50 ),
@ Title varchar (250 ),
@ List2_id varchar (10 ),
@ Pagesize int,
@ Page int
AS
If @ tablename = 'tiku _ koushi'
Begin
Declare @ ks int
Declare @ str varchar (200)
Set @ ks = @ pagesize * (@ page-1)
If not exists (select * from dbo. sysobjects where id = object_id (n' [dbo]. [temp_table91] ') and OBJECTPROPERTY (id, n'isusertable') = 1)
Begin
Select * into temp_table91 from tiku_koushi where
Title like '%' + @ title + '%' and list2_id = @ list2_id order
By id desc
Set rowcount @ pagesize
Set @ str = 'select * from temp_table91 where id not in
(Select top '+ str (@ ks) + 'id from temp_table91 )'
Execute (@ str)
Drop table temp_table91
End
End
GO
4. search_koushi.asp
<! -- # Include file = "conn. asp" -->
<%
Line = 6
If request ("page") = "" then
Page = 1
Else
Page = request ("page ")
End if
If page <1 then
Page = 1
End if
Title = trim (request ("title "))
List2_id = trim (request ("list2_id "))
Set rs21_conn.exe cute ("sp_c 'tiku _ koushi ','" & title & "','" & list2_id &"'")
Pagecount = CInt (rs2 (0) \ line)
If (CInt (rs2 (0) mod line) = 0 then
Pagecount = pagecount
Else
Pagecount = pagecount + 1
End if
If CInt (page)> = pagecount then
Page = CInt (pagecount)
End if
Str = ""
Str = str & "page =" & page & "& title =" & title & "& list2_id =" & list2_id
Set rs1_conn.exe cute
("Sp_search_tiku 'tiku _ koushi ','" & title & "','" & list2_id & "','" & line & "','" & CInt (page) &"'")
If rs. eof then
Response. write "no record"
Else
%>
<Html>
<Head>
<Style type = "text/css">
Td {font-size: 12px ;}
A {text-decoration: none ;}
</Style>
<Script language = "javascript">
</Script>
</Head>
<Body>
<Table width = "518" border = "1" bordercolorlight = "000000"
Bordercolordark = "# ffffff"
Align = "center" cellpadding = "0" cellspacing = "0">
<! -- DWLayoutTable -->
<Tr bgcolor = # dfdfdf>
<Td width = "454" align = "center" height = 24 valign = "middle"> Questions </td>
<Td width = "63" align = "center" valign = "middle"> Delete </td>
</Tr>
<% Do until rs. eof %>
<Tr height = 22>
<Td valign = "middle"> · <a href = void (0 )"
Onclick = "window. open ('editkoushi. asp? Id = <% = rs ("id ") %> & page = <% = page %> & title = <% = title %> & list2_id = <% = list2_id %> ', '', 'width = 518
Height = 160 left = 100 ') ">
<% = Rs ("title") %> </a> </td>
<Td align = "center" valign = "middle"> Delete </td>
</Tr>
<%
Rs. movenext
Loop
%>
<Tr align = "left" valign = "middle" bgcolor = "efeff6"
Height = 22>
<Td colspan = "2" style = "padding-left: 6px;">
<A href = "search_koushi.asp? Page = <% = 1%> & title = <% = title %> & list2_id = <% = list2_id %> "> homepage </a> <
Href = "search_koushi.asp? Page = <% = page-1%> & title = <% = title %> & list2_id = <% = list2_id %> "> previous page </a> <
Href = "search_koushi.asp? Page = <% = page + 1%> & title = <% = title %> & list2_id = <% = list2_id %> "> next page </a> <
Href = "search_koushi.asp? Page = <% = pagecount %> & title = <% = title %> & list2_id = <% = list2_id %> "> last page </a>
Total <% = pagecount %> pages: <% = page %>/<% = pagecount %> page
Total <% = rs2 (0) %> records </td>
</Tr>
</Table>
</Body>
</Html>
<%
Rs2.close
Set rs2 = nothing
Rs. close
Set rs = nothing
End if
%>
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.