ASP Fast implementation of Dynamic Web page _ Application Skills

Source: Internet
Author: User
Tags array definition connection pooling dsn error handling http cookie odbc ole
This is a detailed article on how to streamline code and ASP features to get the fastest execution speed. For an impatient user, any delay between pressing the user button and appearing on their screen may mean that they will go to other sites? If you are a commercial site, this could mean losing potential sales.
We don't have any way to control the bandwidth of our users, but we do get the best possible through optimizing the ASP site. Most of the potential ascension is through system change rather than tightening code, an inappropriate idea is that once you encounter system efficiency problems, the system * * * * * * * * * * * * * * * * * * * * to upgrade the system.
First, which factor may affect the ASP's * energy? Unfortunately, there are many factors. Here are just a few of them:
Available bandwidth
Speed of processors and other hardware on the server
Other programs running on the server (like those OpenGL screen saver!) )
Database connection mode, connection pooling, database system itself (Oracle better than SQL Server,sql Server better than Access)
The language you are using
Stored procedures are superior to line-SQL statements
Using compilation components instead of VB or JavaScript, good ASP programming experience, such as error handling
Some of the above factors may have been widely noticed by developers with knowledge of IIS, but others may be a very complex issue for them. In this article, you will try to explain every factor that affects asp*, and let's take a look at the main things we can do in a few milliseconds of shaving.
ASP script Size
Do you have a script page (and other pages) that are longer than the required length? This is the first implementation will reduce the ASP * can things. ASP scripts are useful when it comes to getting information and formatting output, but scripts are also interpreted on a row-by-line basis, so the longer your script is, the longer it takes to execute it.
If your script is huge, what can you do to reduce the length of the script? Here are a few suggestions:
You can convert them to server-side components, that is, to make a VB Dynamic link library dll or convert it to an precompiled component through an advanced Windows programming language or an appropriate COM interface language? and register them on the server side. The quick Guide is available in
Http://www.webdevelopersjournal.com/articles/activex_for_asp.html find. Compiling a well written ActiveX component can greatly improve the * and protect your software (scripts), especially if you publish your ASP site on a third-party host.
Because the scripts are executed on a row-by-line basis, eliminating redundant scripts or creating more efficient scripts can improve * energy. If you have hundreds of lines of code in a single ASP file, you can do a good job of dividing users, trading and data services. In fact, if you do this, you might find some redundant code: If you need to output a few tables, you can write a generic function to output a table, just call it multiple times.
When you talk about the size of an ASP script, you have to mention the size of the included file. When you use a containing file, the entire containing file is loaded, and when the containing file is included, it is equivalent to writing that part of the code in the ASP file itself. So if you define a lot of common methods and definitions in a lengthy inclusion file, realize that when you include the file, whether you want to use every method or definition inside it, it's all loaded. ASP caches all of the unwind code, which reduces lookup efficiency in this case, the inclusion file must be split into smaller, modular files. Also understand that the inclusion file is considered a separate page request by the server, and using too many include files can affect download times.
!--#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? ' Call procedure Main
</SCRIPT>
If your script is lengthy, use response.isclientconnected. This means that your server CPU can avoid looping while the client is no longer connected to the server.
<%
' Check if the client is still connected
If not response.isclientconnected Then
' Still connected, ' the handler
Else
' Disconnect
End If
%>
Interspersing ASP and HTML
Does everyone do this? When we output the table, we switch between the ASP and the 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 you use the IF statement:
<%
If not session ("dbopen") Then
%>
<%
Else
%>
<%
End If
%>
In these cases, the script * can improve the * energy by writing the server-side script together and generating HTML code with Response.Write. Like what:
<%
If not session ("dbopen") Then
Response.Write "Else
Response.Write "End If
%>
In the case of large scripts and a lot of scripts, you will be able to see the improvement. Note that the use of the <% tag is avoided, so that the * can be improved, and the ASP does not need to compute the ASCII code of the characters when executing the script.
Session Status
Undoubtedly, the ability to maintain a certain state through session in an ASP is a very powerful feature. However, it will affect your * energy. Obviously, the scalability of your site becomes another problem if you limit the use of sessions. However, session consumes server resources for each user.
If you don't use the session variable, or actually you don't have to use it? Is it a trick to use hidden form fields to hold data in a database and query strings? So you should ban session status. You can use the following declaration to prohibit the use of session:
@EnableSessionState = False
This way, the ASP will no longer check session information.
If you have to rely on session state, you should avoid storing large amounts of data in the Session object. The session in IIS is persisted when the HTTP cookie of the client is available, causing the memory occupied by the session to be occupied until the session terminates or times out. This way, if many users use your program at the same time, your server resources may be depleted.
Database access
Database access is a must for trouble? Accessing the database will slow down your program intensely, but obviously, without a database, many sites will become worthless. But using stored procedures to access databases instead of embedded SQL statements, you can promote potential * energy. By using stored procedures and ActiveX Data Objects (ADO), they also have a good flexibility *. Output data from stored procedures whenever possible.
Make sure your database is indexed, as it can directly improve the efficiency of your program. Also, try to run Update statistics (update Statistics) on your database server to help track your data distribution so that your database can transform query execution based on that information. Note that some databases, such as Ms Access, are really acceptable in an enterprise-level program? SQL Sever 7.0 or Oracle is a better bet.
Let SQL work as it was designed, it can count (statistics), connect (join), sort (sort), and group data. When you can write a query to do these things, do not use the other language to implement.
The following is the simplest 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), 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 OLE DB provider technology to connect to your database instead of using a DSN connection. You no longer have to plead with your ISP (or database agent/webmaster) to create a System DSN for you, and you don't need to change the configuration when you remove the Web file.
OLE DB is between the ODBC layer and the application. In your ASP page, ADO is a "application" above odedb. Your ADO calls are first sent to OLE DB, which is then sent to the ODBC layer. However, you can connect directly to the OLE DB layer, and if you do, you can see the server-side improvement. However, how do I connect directly to OLE DB?
If you use SQL Server 7, connect to the database using the following connection code:
strconnstring = "dsn= ';D river={sql SERVER};" & _
"UID=MYUID; Pwd=mypwd; "& _
"DATABASE=MYDB; Server=myserver; "
The most important parameter is the driver= part. If you want to bypass ODBC and use OLE DB to connect to SQL Server (which 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 something wrong here?
Now you may find it a little strange: what are the main points of our new approach to linking? Why not use the standard Dsn-less/system DSN approach? Well, according to Wrox's test results in his book ADO 2.0 Programmer's Reference, if you use OLE DB connectivity and DSN or Dsn-less connection method comparisons, you will find the following improvements:
* Can compare:
SQL Access
Oledbdsnoledbdsn
Connection time: 18?82? Connection time: 62?99
Query 1,000 records time: 29005400 query 1,000 record time: 100950
Note: This result is available on pages No. 232 and 233 of Wrox's "ADO 2.0 Programmer's Reference" book. The unit of time is milliseconds, and query 1,000 record time is computed from a server-side cursor (when using a client cursor, there is little difference between OLE DB and the DSN recordset).
ASP decoding problem:
Reduce the number of HTTP round-trip requests as much as possible by confirming user input at the client. If browsers have the ability to support JavaScript or other scripts, use their power to free more server resources.
The following VBScript runs in the client browser and is used to authenticate user information before submitting 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>
<formmethod= "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 accessed faster by the ASP script engine than global variables because the entire name domain is not searched. Avoid changing the array definition. It is more efficient to simply allocate enough size at the first initialization time. In this case, you may waste some memory, but you gain the advantage of speed. This technique is clearly available when the server is heavily loaded.
If you need to refer to an object that does not necessarily need to be used, it is best to use the <OBJECT> tag instead of the Server.CreateObject method. Using Server.CreateObject causes an object to be created immediately, whereas a <OBJECT> tag does not immediately establish an object if you use the <object> definition without using the object, you will not waste resources.
For example, the following example is a Application-scope Ad Rotator object that uses the <OBJECT> tag to build a real
Cases:
<object runat=server scope=application id=myads progid= "MSWC. AdRotator ">
</OBJECT>
After you store the Ad Rotator object into application, you can access the object in the following syntax on any program's page
<%=myads.getadvertisement ("CustomerAds.txt")%>
Open the ' Option Explicit ' switch. In VB and VBScript, you can use variables without an explicit declaration. But this option can be used to identify variables, so that you can write variables well and help improve * energy. An undefined local variable slows because before it is established, the namespace must be searched before it knows if the variable exists. get rid of it and make each variable clearly defined (first defined and then used).
This is a good habit, it may trap typos, so much quicker.
Do not use the Server.MapPath method unless you really need to use it. If you know the real path, use the real path. Using MapPath requires IIS to retrieve the current server path, which means that you have to send a special request to the server, which means it lowers the * energy. Another approach is to store the path in a local variable and use it when it is needed so that the server does not need to be searched more than once.
Check out how you do it.
You can use tools to measure your system's ability, such as System * monitor, Netmon and Perfmon. Test web* can be used WCAT (Web Capacity analysis Tool). Using 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 a guide to optimizing your server and network configuration. WCAT is specifically designed to estimate the amount of customer work that Internet services (or Windows NT) and IIS can respond to in Windows 2000
(simulation). For more information, refer to the IIS Resource Kit (Resource Kit). There are also lengthy WCAT user guides that have a download link in the MSDN Online Web Sorkshop site. If you are serious about your ASP *, be sure to get the tool.
To optimize your application *, your Web application will run more smoothly. Do not affect the server's * energy if it is not really needed.
ASP using stored procedures to implement data paging
First, create a 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] (COLLATE)
Chinese_prc_ci_as NULL,
[LIST2_ID] [Char] (a) COLLATE
Chinese_prc_ci_as NULL
) on [PRIMARY]
Go
Second, stored procedure 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
Third, stored 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
(select Top ' +str (@ks) + ' IDs from temp_table91 ') '
Execute (@str)
drop table Temp_table91
End
End
Go
Four, 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 Rs2=conn.execute ("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 Rs=conn.execute
("Sp_search_tiku ' Tiku_koushi ', '" &title& ", '" &list2_id& "', '" &line& ", '", "&cint page) & "'")
If Rs.eof Then
Response.Write "No Record"
Else
%>
<style type= "Text/css" >
td{font-size:12px;}
A{text-decoration:none;}
</style>
<script language= "JavaScript" >
</script>
<body>
<table width= "518" border= "1" bordercolorlight= "000000"
bordercolordark= "#ffffff"
align= "center" cellpadding= "0" cellspacing= "0" >
<!--dwlayouttable-->
<tr bgcolor= #dfdfdf >
&LT;TD width= "454" align= "center" height=24 valign= "Middle" > Questions </td>
&LT;TD width= "align=" "Center" valign= "Middle" > Delete </td>
</tr>
<% Do until rs.eof%>
<tr height=22>
&LT;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>
&LT;TD align= "center" valign= "Middle" > Delete </td>
</tr>
<%
Rs.movenext
Loop
%>
<tr align= "left" valign= "Middle" bgcolor= "Efeff6"
Height=22>
&LT;TD colspan= "2" style= "PADDING-LEFT:6PX;" >
<a href= "Search_koushi.asp?page=<%=1%>&title=<%=title%>&list2_id=<%=list2_id%>" > Home </a> <a
href= "Search_koushi.asp?page=<%=page-1%>&title=<%=title%>&list2_id=<%=list2_id%>" > Prev </a> <a
href= "Search_koushi.asp?page=<%=page+1%>&title=<%=title%>&list2_id=<%=list2_id%>" > next page </a> <a
href= "Search_koushi.asp?page=<%=pagecount%>&title=<%=title%>&list2_id=<%=list2_id%>" > Last </a>
Total <%=pagecount%> page Current page: <%=page%>/<%=pagecount%> page
Total <%=rs2 (0)%> Records </td>
</tr>
</table>
</body>
<%
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.