How to enhance the ASP program performance
--- Excerpted from the "Tianji Net"
Introduction performance is a very important feature. You need to design a performance indicator in advance, otherwise you will rewrite the program for this. That is to say: How do you optimize the ASP program? This paper proposes some techniques that optimize ASP applications and VBScript, many techniques and defects have been discussed. The recommendations listed here have been tested at http://www.microsoft.com and other sites, they have work very well. This article assumes that you have basic knowledge developed by ASP, including VBScript or JScript, ASP applications, ASP SESSION, and other ASP built-in objects (Request, Response, and Server). Usually, ASP execution performance is far more than just ASP code itself! The end of this article lists resources related to performance, which contains ASP and non-ASP portions, including ActiveX Data Objects (ADO), Component Object Model (COM), Database, and Internet Information Server (IIS) )Configuration. In addition to these, there are some very good links worth watching. Tips 1: The data typically used in the web server is typically: the ASP page retrieves the data from the background store, then forms the result in the hypercurrent markup language (HTML). Regardless of the speed of the database, retrieving data from memory is much faster than from the background storage device. Reading data from a local hard drive is usually very fast. Therefore, improve performance can be implemented by data on the cache server, whether it is cacked in memory, or in the local hard disk. The cache is a classic "spatial change time". If the cache is appropriate, you can see a significant performance improvement. In order to make the cache valid, it is necessary to ensure that cache data is often reused, and it is also cumbersome. The cache filled with old data is a waste of memory. The data that does not change often is a better object of the cache because it is not necessary to consider the synchronization operation after this data update. Combination box, reference table, DHTML code, extended tag language string, menu, and site configuration variables (including data source names DSNS, Internet protocol address IP, and web paths) are well cache objects. Note: To cache data expressions instead of the data itself. If an ASP page changes frequently and firms (such as the entire product catalog), you should consider pre-generating HTML instead of each time a request is taken. Tips 2: Application and Session objects in the data ASP that are cached in Application or Session objects are a convenient container that caches data in memory. You can assign data to Application and Session objects, which will remain in memory during HTTP calls. The data in the session is for each user, and the data in Application is shared by all users. When will I need to load data in Application and Session? Typically, the data is loaded when the application starts or when the session begins. In order to load data at this time, add the appropriate code to Application OnStart () or Session OnStart (). These functions are located in the file global.asa, and if it does not exist, add it. You can also transfer it when the data is first required, add code to the ASP page, check if the data exists, if you don't find it, you will be transferred.
Here is an example that represents a classic performance processing technology called "lazy evalution": until it is needed, then calculate. The example is as follows: <%
Function geteMPloymentStatusList
DIM D
D = Application ("EMPLOYMENTSTATUSLIST")
IF d = "" "
'FetChemploymentStatusList Function (Not Shown)
'Fetches Data from DB, Returns an Array
D = fetchemploymentstatuslist ()
Application ("EMPLOYMENTSTATUSLIST") = D
END IF
GetEmploymentStatusList = D
END FUNCTION
%>
A similar function code can be written for different data. What format should be saved in? Any variable type can be used because all script variables are different. For example, it can be saved as a string, integer or data. Typically, the contents of the ADO record set are stored in one of these variable types. In order to remove data from the ADO record, you need to copy data from the VBScript variable, each time a field. Use any ADO record set function functions getRows (), getString () or Save () (ADO 2.5) is very fast and simple, here there is a function, describing how to use getRows () Return record set data:
'Get Recordset, Return as an Array
Function FetChemploymentStatusList
DIM RS
SET RS = CreateObject ("AdoDb.Recordset")
Rs.open "Select StatusName, Statusid from Employeestatus", _
"DSN = Employees; UID = SA; PWD =;"
FetChemploymentStatusList = rs.getrows () Return Data as an Array
Rs.close
SET RS = Nothing
END FUNCTION
A deeper tip of the above code is to cache HTML for the list. Here is a simple example:
'Get Recordset, Return AS HTML OPTION LIST
Function FetChemploymentStatusList
DIM RS, FLDNAME, S
SET RS = CreateObject ("AdoDb.Recordset")
Rs.open "Select StatusName, Statusid from Employeestatus", _
"DSN = Employees; UID = SA; PWD =;"
S = "
Set fldname = rs.fields ("statusname") 'Ado Field Binding
Do Until Rs.eof
'Next Line Violates Don't do string control,
'But it's ok because we are building a cache
S = S & "
rs.movenext
Loop
S = S & " SELECT> & VBCRLF
Rs.close
SET RS = Nothing 'See Release Early
FetChemploymentStatusList = S 'RETURN DATA AS A STRING
END FUNCTION
In a suitable environment, you can cache the ADO recordset itself in Application or Session, but there is 2 points:
ADO must be free thread mark
Need to use Disconnected Recordset
If you can't guarantee the above two conditions, don't cache the ADO record set because this will produce a lot of dangers. When the data is saved in the Application or Session, the data will remain, unless the program changes it, the session variable expires or the web application is restarted. What should I do if the data needs to be updated? You can call only the ASP page that only administrators can access to update the data, or automatically update the data through the function periodic. In the following example, the clock tag is saved with the cache data. After a period of time, the data is refreshed.
<%
'Error Handing Not Shown ...
Const update_interval = 300 'Refresh Interval, In Seconds
'Function to Return the Employment Status List
Function geteMPloymentStatusList
UpdateemPloymentStatus
GetEmploymentStatusList = Application ("EmploymentStatusList")
END FUNCTION
'Periodically Update The Cached Data
Sub UpdateEmploymentStatusList
DIM D, STRLASTUPDATE
StrlastUpdate = Application ("Lastupdate")
IF (strlastupdate = ") or _
(Update_Interval 'NOTE: Two or More Calls Might Get in here. This is okay and willimpli 'Result In a Few Unnecessary Fetches (There Is A Workaround for this) 'FetChemploymentStatusList Function (Not Shown) 'Fetches Data from DB, Returns an Array D = fetchemploymentstatuslist () 'Update the application object. Use application.lock () 'TO Ensure Consistent Data Application.lock Application ("EmploymentStatusList") = Dapplication ("Lastupdate") = CSTR (now) Application.unlock END IF End Sub There is another example, see World's Fastest Listbox With Application Data. It must be aware that the array of cache large capacity in the session or Application object is not a good method. The rules of the scripting language must first establish a temporary backup of the entire array before accessing any elements in arrays. For example, if you cach a 100,000 element in the Application object, which contains the corresponding relationship with the US Postal Code and the local meteorological station. The ASP must first copy all 100,000 weather station information to the temporary array, then Select one of the strings for processing. In this case, create a custom component, writing a method storage weather station information, is a very good way. Tips 3: Cache data and HTML pages on the web server disk sometimes, with "many" data to cache in memory. "Many" are relatively, depending on how much memory, cache item is used, and the frequency of retrieving data. In any case, if you need to cache a large amount of data in memory, consider making caches on the web server hard drive in a text or XML file format. Of course, it is also possible to mix the use of hard drive cache data and memory cache data to achieve the best cache. Note: When testing the performance of a single ASP page, retrieving data from disk is not necessarily faster than retrieving data from the network database, but the cache reduces the call of the network database. This will significantly improve the throughput of the network during large scale call. The result of caching a fee is very useful, such as a complex stored procedure, or a large number of result data. ASP and COM provide several tools based on disk buffering configurations. The SAVE () and open () functions of the ADO record set are responsible for saving and tune the record set on the disk. There are also some components: Scripting.filesystemObject allows you to create, read, and write files MSXML, Microsoft XML parser comes with Internet Explorer, supports saving and loading an XML document Lookuptable objects (for example on MSN) is a good choice to transfer from disk to a simple list. Finally, consider the expression of the cache disk data, not the data itself. The pre-processed HTML can be stored as .htm or .asp files, the link directs them directly. These processes can be processed using commercial tools such as XBuilder or Microsoft SQL Server Internet. Moreover, the HTML program block can also be included in the .asp file. Similarly, you can also read the HTML file from the disk using FileSystemObject, or use XML for Early Rendering to do this. Tips 4: Avoid cache data in Application or Session objects in Application or Session objects in Application or Session objects is a good way, but cache COM objects have severe defects. This work is very attractive in Application or Session objects, which is very attractive, but very unfortunate, many COM objects, including object components written with Visual Basic 6.0 or previous versions, when stored in Application or Session objects It will produce a serious bottleneck problem. In particular, it is possible to generate bottleneck problems when the component is written is not very light. A light component is a component that is marked with ThreadingModel = Both, where the free thread is arranged (FTM), or the ThreadingModel = Neutral (neutral mode is new features in Windows 2000 and COM ). The following components are not lightweight: Free-threaded components (unless they are set to FTM) Apartment-threaded component SINGLE-Threaded component Configured Components are not light components unless they are neutral-threaded. The Apartment-Threaded component and other non-light components work well within the page, that is, they are created and released in a single ASP page. What happens if a non-light component is cached? Non-light components cached in the session object will "lock" sessions. ASP maintains a working thread pool that responds to requests, usually, new requests are controlled by the first available working thread. If a session is locked in a thread, the request is forced to wait for the related thread to become available. Here is a class ratio: You go to a supermarket, choose some food, and pay at the No. 3 payment. Since then, as long as you buy food in that supermarket, you will go to the No. 3 card, although there are fewer other payers. Tips 5: Do not cache database connection cache ADO connections in Application or Session objects is usually not a good policy. If a connection object is stored in the Application object and is used on all pages, all pages will compete for the connection. If you are stored in the ASP Session object, you will open the database connection for each user. This will defeat the use of the connection pool and the unnecessary high cost pressure is applied to the web server and the database. To replace the cache database connection, you can create and release the ADO object in each ASP page of ADO. This will be very effective because IIS has a built-in database connection pool. More specifically, IIS automatically processes OLEDB and ODBC connect pools, which will ensure efficient operation of each page created and released. Since the connected record set stores a reference to the database connection, do not cache the connected record set in the Application or Session object. However, the record set of the disconnected type can be safely cached, and they do not save the reference for the corresponding database connection. In order to disconnect the record, do 2 steps below: SET RS = Server.createObject ("AdoDb.Recordset") rs.cursorlocation = aduseclient 'Step 1 'Populate the Recordset with data RS.Open StrQuery, STRPROV 'Now Disconnect The Recordset from the data provider and data source rs.activeConnection = Nothing 'Step 2 For more information on connecting pools, please visit Ado and SQL Server. Skills 6: Smart using session object session when used on busy sites, there are several defects. Busy means: There are hundreds of pages per second on site, or have thousands of access users. This trick is very important for those sites that require a strong level of extension, that is, these sites: they use multiple servers to complete data loading or handle a lot of fault tolerance. For small sites, such as internal network Intranet, Session is very pronounced. Reebred again, the ASP automatically creates a session for each first click on the web server, each session occupies approximately 10 kb memory, and the survival is 20 minutes by default. Using the SESSION's biggest problem is not performance, but scalability, session cannot span multiple web servers, once a session is created on a server, its data resides there. This means that if you use session on the Web, you have to design a policy for each user who stores the SESSION server. This is why users "stick" on the web server, the term "sticky sessions" comes from this. If the web server encounters an obstacle, "Stuck" user will lose their session status because the session is not retained on the disk. Performing sticky session strategies include hardware and software solutions, such as Network Load Balancing in the Windows2000 Advanced Server, and Cisco's Local Director, but exchange these to sacrifice certain scalability. Application objects cannot cross the server. If you need to share and update Application data in a web group, you need to use the background database. However, read-only Application data is still useful in the Web group. Many of the tasks requires a strict site to set up at least 2 web servers, so when designing strict tasks, you need to perform "Sticky Sessions", or simply avoid using Session, and you can also take other saved user status to Management technology of independent web servers. If you don't use Session, you must confirm that you turn it off, which can be implemented via the Internet Service Manager. If you decide to use session, you can minimize their impact in several ways. You can move content that doesn't require session (such as a Help Screen, Accessor Area, etc.) to the standalone ASP application that is turned off in the session. On the foundation page, you can give an indication to the ASP, so it doesn't need to use session. Add the following code directly to the header of the ASP page: <% @ enablessionState = false%> A good explanation using this indication is to create an interesting issue in the frame structure. ASP ensures that only one request from Session is executed at a time, which ensures that if the browser requests multiple pages for a single user, only one ASP request can accept the session at that time, so avoid accessing the session object. Multithreaded problem. Unfortunately, all pages in the frame structure will be displayed in a continuous order, one pick one, not simultaneous, so users must wait for a long time in order to see the entire framework. The rule is: If a certain frame page does not use session, you must tell the ASP to use @ enablessionsState = false. In addition to using the session object, there are many other severings of other management session. For small quantities (less than 4KB), we usually recommend using cookies, query string variables, and form hidden domains. For large amounts of data like shopping carts, the background database is the most appropriate choice. Tips 7: Load the code into a COM object If you want to write a lot of VBScript or JScript, in order to make performance, you can write the code as a COM object and compile. Compiling code is basically a fast than the interpretative code, and the compile component object can access other COM objects via "Early Binding", which is more effective than calling components in the script. There are many advantages to do this: COM objects are beneficial to independent expressing rules from business rules COM object makes the code reuse possible Many developers have found programs with VB, C or Visual J , more easily debugging than ASP The COM object also has a disadvantage, including initial development time and needs for different programming skills. Note that a small amount of ASP code is a COM object component will not be beneficial, but it may cause loss of performance, thereby losing the advantage of compiling code. How to combine the use of ASP scripts and COM objects to achieve optimal performance is a test problem. We note that Microsoft has improved the performance of scripts and ado on Windows 2000 / IIS 5.0, whereby the introduction of the IIS5.0 version reduces the performance advantages of compiling code. Tips 8: Use option expedition to use Option Explicit definition in the ASP file, and place it to the head of the ASP file, forcing developers to declare all variables before use. Many programmers believe that this is very useful when application debugging, because it avoids possible possible type variables and creating new variables. Perhaps more importantly, the declared variable is much faster than non-declared variables. Skill 9: Copy often uses data to the script variable When you use a COM object in the ASP, you should copy the frequently used object data into the script variable, which reduces the method of calling the COM object. These calls are relatively expensive than access script variables. Use this technique when you access the Collection and Dictionary objects, also reduces expensive lookup operations. Typically, if you need to access object data over one time, data should be placed in a script variable, and the object data is mainly the request variable (form and query string variable). For example, the site wants to pass a query string variable called UserID, assume that it will be referenced 12 times in a special page, so no need to call Request ("UserID") 12 times, as long as the header of the ASP page is distributed to UserID one Variables, then use it in the page, which saves 11 calls for 11 COM methods. In practice, accessing COM properties or methods is very expensive. The following example shows universal code: foo.bar.blah.baz = foo.bar.blah.qaz (1) if foo.bar.blah.zaq = foo After. bar.blah.abc Then '... After execution, the following things happen: 1, the variable foo is treated as a global object 2, the variable bar is used as a member of the Foo 3, and the variable Blah is treated as a foo. One member of Bar, the variable QAZ is used as a member of foo.bar.blah, call foo.bar.blah.quaz (1) 6, then perform step 1 to 3 to decompose Baz7, decompose Baz as foo.bar One member of .blah 8, then perform steps 1 to 3 to decompose ZAQ9, and then perform step 1 to 3 once the decomposition ABC is as shown above, which is very no efficiency and very slow. The faster method is to write code with VBScript, as follows: set myobj = foo.bar.blah 'do the resolution of blah overcemyobj.baz = myobj.qaz (1) if myobj.zaq = myobj.abc Then' ... if Use VBScript 5.0 or higher, you can write: with foo.bar.blah .baz = .qaz (1) If.zaq = .abc dam ... ... End with Note: This trick can also be applied in VB programming. Tips 10: Avoid redefining arrays do not define arrays again. Considering performance issues, if the physical memory size of the machine is not enough, it is best to set the initial size of the array according to the worst case or the best condition, and then redefine it. The following code shows the use of DIM and Redim: <% Dim MyArray () Redim myarray (2) MyArray (0) = "Hello" MyArray (1) = "Good-bye" myarray (2) = "farewell" .. . 'Some Other Code Where You End Up Needing More Space Happens, Then ... Redim Preserve MyArray (5) MyArray (3) = "More Stuff" MyArray (4) = "Even more stuff" MyArray (5) = "yet More stuff "%> Simply define the initial size of the array to be very good, instead of increasing arrays with Redim. So perhaps waste some memory (if you don't use space completely), but win the speed. Tips 11: Using Response Buffering By opening "response buffering" to buffer a whole page content worth output, this will minimize the amount of data output to the browser, thereby improving overall performance. Every output is much consumed, so the less the effect is, the better the effect. TCP / IP When sending a small amount of large packet, TCP / IP is higher than that of sending a large amount of small packets, because it is slow and constantly transmitted. There are two ways to open Response Buffering. First, you can open Response Buffering throughout the application for the entire application, which is recommended in IIS4.0 and IIS5.0. In the default, response buffering is open. Secondly, on each page, you can place the following code to open Response Buffering: <% response.buffer = true> This code must be executed before any data output to the browser (that is, in any HTML The content is displayed before and before any cookie is set). Typically, open response buffering for the entire application is a good solution. After doing this, you don't have to set up the code as above each page header. A general question about opening Response Buffering is: The user must wait for the entire page to be generated before you can see the content. For a long-running page, you can set the response.buffer = false shut down buffer. Then, a good strategy is to use the response.flush method, which will output all HTML contents to the ASP to the browser. For example, after describing a 100 line of a 1,000-line table, the ASP can use Response.flush to force the output of this 100 row to the browser. At this time, the user can see the first 100 lines of data, the rest The data is being prepared to be generated. Note that an example of the above 1,000-line table output, for some browser, unless any content of the table is encountered, they do not output any content of the table. If so, the table can be split into a number of tables containing a small amount of rows, and then the response.flush output is called after each table is generated. The new version of Internet Explorer displays the content after downloading the entire form, and if the list of the table is defined, the speed of generating the table will be particularly fast. Another problem with the Open Response Buffering is: When generating a very large page, it will consume very large server memory. Skill 12: Batch single-line script and response.write command VBScript syntax <% = expression%> means the value of Expression. If Response Buffering is not open, each such statement will output data into the browser in the form of many small packets, which will reduce program performance. Therefore, please use the following skills: replace multiple line expressions to call to a call, and output with the Response.Write name. For example, in the example below, for each field of each field, only one write operation: