TwentyVIs Improve ASP Performance and Appearance Tips Len Cardinal, Advanced Consultant, Microsoft Consulting Services George V. REILLY Microsoft Iis Performance Lead
Adapted from Nancy Cluts Article Developer Technical Engineer Microsoft Corporation 2000 April 2000
Summary: This article describes how to optimize ASP applications and VBScript.
Directory Skills 1: Cocaine the frequently used data on the web server 2: Cocaine the frequently used data in Application or Session object 3: Cocard data and HTML on disk on the web server 4: avoid non-bustling Components Cacked in Application or Session Objects 5: Do not use database connections in Application or session objects 6: Reasonably use session object skills 7: package code package in COM objects 8: Late to get resources, early Little release resource skills 9: Process external execution process with performance exchange Reliability Tips 10: Using Explicit Options Skills 11: Using local variable tips in subroutines and functions 12: Copy the data commonly used to script variables 13 : Avoid re-determining the dimension tips of the array 14: Use the response buffer tips 15: Batch Inclusive and response.write statement skills 16: If the page takes a long time to complete, use response.isclientConnected skills before execution 17: use
This article describes how to optimize ASP applications and Visual Basic? Scripting Edition (VBScript). This article discusses many traps. The recommendations listed herein have been tested in http://www.microsoft.com and other sites, and the effect is very significant. This article assumes that you have developed ASP, including VBScript, and / or JScript, ASP Application, ASP Session, and other ASP inherent objects (Request, Response, and Server) have basically understood.
Typically, ASP performance depends primarily on many factors other than ASP code itself. We are not in an article to listen out all the information, and we list the resources related to performance at the end of this article. These links cover ASP and non-ASP topics, including ActiveX® Data Objects (ADOs, Component Object Models, Database, and Internet Information Server (IIS) configuration. These are some links we like - must go see. Tips 1: Retrieve data from the typical ASP page that is often used on the web server, and converts the results into hypertileble language (HTML) on the back-end data store. Regardless of the speed of the database, retrieving data from memory is much faster than retrieving data from backend data storage. Reading data from a local hard drive is usually faster than retrieving data from a database. Therefore, the data can be cached on the web server (stored in memory or disk) to improve performance.
The cache is a traditional way of spatial exchange time. If your cached content is correct, you can see performance. To make the cache valid, you must save the data that are frequently used frequently, and to recalculate these data required (moderate) large overhead. If the cache is some old data, it will cause memory waste.
Data that do not change often is a good cache candidate data, because you don't have to worry about the issue of data and database synchronization over time. Combination Box List, Reference Table, DHTML Debris, Extended Markup Language (XML) string, menu item, and site configuration variable (including data source name (DSN), Internet Protocol (IP) address, and web paths) are well cache Candidate content. Note that you can cache the "representation" of the data without causing the data itself. If the ASP page is rare, the overhead of the cache is also large (for example, the entire product catalog), you should consider generating HTML in advance instead of replaying each request.
Where is the data can be slow, what caokes strategy? Typically, the data can be cached in the memory or disk of the web server. The next two techniques tell these two methods.
Tips 2: Cocaine the frequently used data in Application or session objects ASP Application and Session objects provide a convenient container that makes data cache in memory. You can assign data to the Application and Session objects, which are kept in memory between HTTP calls. The session data is stored separately according to each user, and Application data is shared between all users.
When do you load the data into the Application or Session? Typically, the data is loaded when the Application or Session is started. To load data during the Application or Session startup process, the appropriate code should be added to Application_onstart () or session_onstart (). These functions should be in Global.asa, and if not, these functions can be added. This data can also be loaded during the first time. To do this, some code is added (or writing a reusable script function) to check if the data exists, if not, load data. This is a traditional performance technology called "inert calculation" - do not calculate this value before you know that you need a value. E.g:
<% Function GetEmploymentStatusListDim dd = Application (? EmploymentStatusList?) If d = ?? Then 'FetchEmploymentStatusList function (not shown)' fetches data from DB, returns an Arrayd = FetchEmploymentStatusList () Application (? EmploymentStatusList?) = DEnd IfGetEmploymentStatusList = dEnd Function %> You can write similar functions for each data block you want.
What format should store data? Any variant type can be stored because all script variables are variable. For example, you can store strings, integers, or arrays. Typically, you will save the contents of the ADO record set in one of these variable types. To get data from the ADO recordset, you can manually copy the data to the VBScript variable, one field. Use an ADO record set for jury function GetRows (), getString () or Save () (ADO 2.5), speed and easier. The details have exceeded the scope discussed herein, but a function is given below, indicating an array of record set data using getRows ():
(?? ADODB.Recordset)?? 'Get Recordset, return as an ArrayFunction FetchEmploymentStatusListDim rs Set rs = CreateObject rs.Open select StatusName, StatusID from EmployeeStatus ?, _ dsn = employees; uid = sa; pwd = ;? FetchEmploymentStatusList = rs .Getrows ()? Return Data as an arrayrs.closset = Nothingend Function
For further improvements to the above, you can cache the HTML to a list instead of an array. Here is a simple example:
(?? ADODB.Recordset) 'Get Recordset, return as HTML Option listFunction FetchEmploymentStatusListDim rs, fldName, sSet rs = CreateObject rs.Open select StatusName, StatusID from EmployeeStatus ?, _ dsn = employees;?? Uid = sa; pwd =; ? s =?
ADO must be labeled as a free thread must use a disconnected recordset. If you do not guarantee these two requirements, don't cache the ADO recordset. In the following "Non-Agile Components" and "Do not cache the connection", we will discuss the risk of storing COM objects in the Application or Session scope.
When you store the data in the Application or Session scope, the data will remain there until you change it in programming, the session expired or the web application is restarted. What if the data needs to be updated? To manually enforce Application data, you can access the ASP page that only administrators to update the data. Alternatively, you can automatically refresh the data from a function. The following example stores a timestamp with cache data and refreshs data after a while.
<% 'Error Handing Not Shown ... const update_interval = 300' refresh Interval, In Seconds
'Function To Return The Employment Status ListFunction GetEmploymentStatusListUpdateEmploymentStatusgeTEMPLOYMENTSTATUSLIST = Application (? EmploymentStatusList?) End Function
'Periodically update the cached dataSub UpdateEmploymentStatusListDim d, strLastUpdatestrLastUpdate = Application (? LastUpdate?) If (strLastUpdate = ??) Or _ (UPDATE_INTERVAL 'Note: two or more calls might get in here This is okay and will simply.' Result in a few unnecessary fetches (there is a workaround for this) 'FetchEmploymentStatusList function (not shown)' fetches data from DB, returns an Arrayd = FetChemploymentStatusList () 'Update the Application object. Use Application.Lock ()' to ensure consistent dataApplication.LockApplication (? EmploymentStatusList?) = EventsApplication (? LastUpdate?) = CStr (Now) Application.UnlockEnd IfEnd Sub See World's Fastest ListBox with Application Data, there is an example. To know that a large number of buffers in the session or Application object is not a good practice. The syntax requirements of the scripting language must be temporarily copied to the entire array before any element of the access array. For example, if the array of 100,000 elements consists of a string (the array will be mapped to the local weather station) in the Application object, the ASP must first copy all 100,000 weather stations to the temporary array. Then you can extract a string. In this case, a custom component is created with a customization method to store weather stations - or use a dictionary component. Warning everyone, don't pour the baby with the bathing water: the array can quickly find and store the neighboring key data pair in memory. Indexes a dictionary Pesce Core 1 array is much slower. The data structure that provides the best performance should be selected for your actual situation. Tips 3: On the disk of the data and HTML, the data may be too much, the data may be too large, and it cannot be cached in memory. "Too many" is just a saying, you have to see how much memory you want to consume, and the number of items that you need to cache and retrieve the frequency of these items. In any case, if there is too much data, it cannot be cached in memory, consider the hard disk of the web server in the text or XML file. You can simultaneously cocabulate the data in disk and memory, and create the most appropriate caching strategy for your site. Note When the performance of a single ASP page is measured, the data on the disk may not be faster than retrieving data from the database. However, the cache reduces the load on the database and the network. In the case of high load, this can greatly improve overall throughput. This is very effective when the results of the query result (such as multi-table joint or composite stored procedure) or large results are large. Like us, we have to test the advantages and disadvantages of several programs. ASP and COM provide some tools for establishing a disk-based cache scheme. The ADO record set save () and open () functions save and load the record set in the disk. You can use these methods to rewrite the code example in the above Application Data Cache Tip, with the code of the file Save () instead of the code written in the Application object. Some other components can be used for files: Scripting.FileSystemObject enables you to create, read, and write files. The Microsoft® XML parser (MSXML) supplied with Internet Explorer supports saving and loading an XML document. The Lookuptable object (for example, on the MSN) is the best choice for loading a simple list from disk. Finally, it should be considered that the representation of the data is cached on the disk, not the data itself. Pre-converted HTML can be stored on disk with .htm or .asp file, hyperlink can directly point to these files. Using commercial tools, such as XBuilder, or Microsoft? SQL Server® Internet Publishing feature will generate HTML process automation. Alternatively, you can put the HTML code snippet in the .asp file. You can also read the HTML file from the disk using FileSystemObject, or use XML to conversion as soon as possible. Tips 4: Avoid a good practice to cocabulate the non-spacked components in Application or Session objects although a good practice in Application or Session objects, caching COM objects have a serious trap. Typically, people tend to cache frequent COM objects to the Application or Session object. Unfortunately, many COM objects (including all objects written in Visual Basic 6.0 or lower) When stored in Application or Session objects, a serious bottleneck is caused. Specifically, when any inciting component is cacked, the performance bottleneck will cause performance bottlenecks when there is a session or Application object. Agile components are components marked as threadingmodel = Both, which gatches Free-Threaded Marshaler (FTM); or marked as a component of ThreadingModel = Neutral. (Neutral model is a new model of Windows 2000 and COM .) The following components are not agile: The components of the free thread (unless they gather FTM). Unit thread components. Single threaded components. The configured component (MTS) / COM library, and server package / application) is not agile unless they are neutral threads. Unit thread components and other non-agile components are most suitable in page scope (ie, they create and destroy them on a single ASP page). In IS 4.0, components marked as threadingmodel = Both are considered agile. In IIS 5.0, only this is not enough. Components must not only mark BOTH, but also to aggregate FTM. Articles on agility telling how to get FTMs for C components written in Active Template Library. Be careful if the component cache interface pointer, then those pointers themselves must be agile, or must be stored in the COM Shared Tekle (GIT). If you cannot recompile the Both thread component to aggregate FTM, you can mark the component as threadingmodel = neutral. Or, if you don't want IIS to perform agility checks (So you can allow non-spacing components to be stored in the Application or SESSION scope), you can set AsptrackthReadingModel to True in the configuration database. Not recommended to change the AsptrackthReadingModel. If you want to store a non-agile component created by Server.CreateObject in the Application object, IIS 5.0 will appear an error. You can use Storing non-spacing components in the Application scope is even worse. The ASP must create a special thread running a non-spacing component stored in the Application scope. There will be two results: all calls must be collected to this thread, and all calls are all in the length. The "collection" means that the parameters must be stored in the shared area of the memory; perform a context switch that the overhead to the special thread; the method of executing the component; collect the result to the shared area; execute another superflation of another overhead, Return control to the original thread. "Serialization" means that only one method is run each time. Two different ASP workers threads cannot perform multiple methods on the shared component. This eliminates concurrency, especially on multiprocessor computers. Worse, all the components of all non-burn APPLICATION domains share a thread (host STA), so the effects of serialization are even more prominent. What is it? Here are some general rules. If you write objects using Visual Basic (6.0) or earlier, do not cache them in Application or Session objects. If you don't know the thread model of the object, don't cache it. Do not cache non-burn objects, but you should create and release them at each page. The object runs directly on the ASP worker thread, so there is no collection or serialization. If the COM object is running on the IIS server, and if they don't spend the initialization and delete, performance is still available. Note that single-threaded objects should not be used. CAUTION - VB can create a single-threaded object! If you have to use a single-threaded object (such as Microsoft Excel spreadsheet), don't expect to have a high throughput. When ADO is marked as a free thread, the ADO record set can securely cache. To mark the ADO as a free thread, use the Makfre15.bat file, which is usually in the directory // Program files / Common / System / ADO. WARNING If you use Microsoft Access as a database, the ADO should not be marked as a free thread. The ADO record set must also be cut off. In general, if you do not control the ADO configuration in the site (for example, you are a separate software vendor [ISV], you can do not manage your own configuration customer sales web application, it is best not to cache records. Dictionary components are also agile objects. LOOKUPTABLE loads its data from the data file, which can be used to combine block data and configuration information. The PageCache object in duwamish books provides the word classification, and CapRock Dictionary is also available. These objects or their derived objects can constitute the basis of a valid caching policy. Note that scripting.dictionary object is not agile, and should not be stored in the Application or Session scope. Tips 5: Do not cache the ADO connection in Application or Session objects in Application or Session objects is usually very bad strategy. If a Connection object is stored in the Application object and is used in all pages, then all pages will compete for this connection. If the Connection object is stored in the ASP SESSION object, you will create a database connection for each user. This will cause the advantages of the connection pool to be unfair and bring unnecessary pressure to the web server and database. The database connection can be cached, but create and delete the ADO object in each ASP page of ADO. This is very effective because IIS embeds the database connection pool. More specifically, IIS automatically enables OLEDB and ODBC connection pools. This ensures that it will be valid on each page. Because the connected record set stores a reference to the database connection, you should not have a connection to the Connected Records in the Application or Session object. However, you can safely cache disconnected recording sets, which are not saved to its data connection. To disconnect the record set, do the following two steps: SET RS = Server.createObject (? AdoDb.recordset?) Rs.cursorlocation = aduseclient 'Step 1 'Populate the Recordset with Datars.Open Strquery, StrProv 'Now disconnect the recordset from the data provider and data sourcer.activeconnection = nothing' Step 2 More details on connecting pools can be found in the ADO and SQL Server reference materials. Skill 6: Reasonably uses the session object. Since we have discussed the advantages in Application and Session, it is now discussed to discuss issues to avoid using the session object. As discussed below, when used with a busy site, Session has several disadvantages. "Busy" means that it is generally referring to a second to ask a few hundred points or thousands of sites at the same time. This technique is for a level that must be extended - that is, those sites that use multiple servers to handle loads or implement fault tolerance - even more important. For smaller sites, such as intranet sites, you will inevitably increase the system overhead. Briefly, ASP automatically creates a session for users accessing the web server. Each session requires approximately 10 KB of memory overhead (the most important thing is to store in session), which makes all requests slow down. The session kept valid until the configuration of the timeout period (usually 20 minutes). The biggest problem of Session is not performance, but scalability. SESSION cannot span several web servers, once you create session on a server, your data is left there. This means that if you use Session in a web server group, you must design a policy to send each user request to the server where the user session is located. This is called "sticking" on the web server. The term "viscous session" is derived from here. If the web server crashes, "sticking" users will lose their session status because the session is not sticky to the disk. Strategies to implement viscous sessions include hardware and software solutions. Solutions such as network load balancing in Windows 2000 Advanced Server and Cisco Local Director can achieve viscous sessions, and the cost is to lose a certain degree of scalability. These solutions are not perfect. It is not recommended to deploy your own software solution (we used to use ISAPI filters and URL conversions, etc.). Application objects do not cross multiple servers, if you must share and update Application data across the web server group, you must use the backend database. However, read-only Application data is still useful in the web server group. If only because it is to increase the runtime (handling failover and server maintenance), most critical tasks must be deployed at least two web servers. Therefore, when designing a key task application, "sticky session" must be implemented, or simply avoid using session, and any other state management technology that stores user status on a single web server. If you don't use Session, you must turn them off. You can do this with the Internet Services Manager (see the ISM document). If you decide to use Session, you can use some ways to mitigate their impact on performance. You can move the content of the session (such as a help screen, visitors, etc., etc.) to another. You can prompt ASP by page-by-page, you no longer need the session object on this page, using the following on the ASP page, the top instruction: <% @ EnablesessionState = false%> It is a good reason to use this command that these session has a meaning problem in the frameset set. ASP guarantees that only one request is executed at all times. This ensures that if the browser requests multiple pages for a user, only one ASP requests contact SESSION, which avoids the multi-threaded problem that occurs when accessing the session object. Unfortunately, all pages in a framework will be displayed in a serial manner, one pick one, not simultaneously. Users may have to wait for a long time to see all the frameworks. The story of this story: If some framework sets do not rely on Session, you must use the @ EnableSessionState = FALSE instruction to tell ASP. There are many ways to manage the SESSION state to replace the use of the Session object. For a small amount (less than 4 kb), we usually recommend using cookies, queryString variables and implicit variables. For greater data, such as shopping trolley, backend databases are the most suitable choices. There are many articles about status management technology in the web server group. For more information, see Session Status Reference. Tips 7: Package the code in the COM object If you have many VBScript or JScript, you can often move the code into the compiled COM object, so that performance can be improved. Compiled code is usually run faster than the interpreted code. Compiled COM objects can access other COM objects with "early binding", "Binding" is a more efficient way to call COM objects than "evening binding" used by the script. There are also some advantages in the COM object (except for performance): The COM object is conducive to the separation of logic and business logic. COM objects ensure that the code is reused. Many developers have found that code written in VB, C or Visual J is more easily debugged than ASP. The COM object also has a disadvantage, including initial development time and requires different programming techniques. Note that a small amount of ASP can cause performance to decline without performance improvements. This happens when a small amount of ASP code is encapsulated into a COM object. In this case, the system overhead of creating and calling the COM object exceeds the advantage of compiled code. Tests should be repeated to determine what kind of ASP script and combination of COM object code produces the best performance. Note that in terms of Microsoft Windows NT? 4.0 / IIS 4.0, Windows 2000 / IIS 5.0 has great improvements in scripting and ADO performance. Therefore, with the introduction of IIS 5.0, compiling code is reduced than the performance advantages of ASP code. For detailed discussion on the advantages and disadvantages of using COM in ASP, see ASP Component Guidelines and Programming Distributed Applications With and Microsoft Visual Basic 6.0. If you deploy COM components, you will test them in your load. In fact, all ASP applications should be subject to load testing. Skills 8: Listen to the resource, release resources, here is a tip for your reference. In general, it is best to obtain resources late and release resources earlier. This applies to COM objects and file handles and other resources. This optimization method is mainly used in the ADO connection and record set. When you use the recordset, you should release it immediately after displaying a table and its data, rather than waiting until the end of the page is released. Setting the VBScript variable to Nothing is the best practice. Don't let the record set beyond the scope. Moreover, to release any associated Command or Connection object (do not forget to call Close ()) before setting the record set or connection to = Nothing. This will shorten the database for you to prepare resources, and release the database to the connection pool as soon as possible. Skill 9: Process External Execution Process with performance exchange Reliability ASP and MTS / COM have configuration options, allowing you to take care of reliability and performance. When establishing and deploying an application, you should know how to take into account the performance of both. The ASP option can configure an ASP application to run in one of three ways. In IIS 5.0, the term "isolation level" is introduced to illustrate these options. These three isolation stages are low, intermediate and advanced respectively: Low level isolation. This is supported in all of IIS, and is the fastest. It runs ASP in inetinfo.exe, and inetinfo.exe is the main IIS process. If the ASP application crashes, IIS will also crash. (To restart IIS in IIS 4.0, Web site administrators should use tool monitoring sites such as inetmon, if the server fails, enable batch files to restart the server. IIS 5.0 introduced reliable restart, this The method can automatically restart the server that has failed.) Intermediate Isolation. IIS 5.0 introduces this new level, which is called the process level because ASP runs outside the IIS process. In intermediate isolation, all ASP applications configured as intermediate isolation are shared with a process space. This reduces the number of processes required to run multiple processes outside a server. Intermediate Isolation is the default isolation level in IIS 5.0. Advanced isolation. This level is supported in IIS 4.0 and IIS 5.0, and advanced isolation is also processed. If the ASP crashes, the web server will not crash. When the next ASP request, the ASP application will automatically restart. In advanced isolation, each ASP application that is configured as advanced isolation is running in its own process space. Doing so protects ASP applications without interfering with each other. Its disadvantage is that it requires every ASP application to have a separate process. When many applications must be run on one server, the system overhead will increase. Which option is best? In IIS 4.0, the process runs outside the process will significantly reduce performance. In IIS 5.0, many improvements have been made to minimize the overhead generated by the processes running the ASP application. In fact, in most tests, the ASP process outside IIS 5.0 is run faster than within the process in IIS 4.0. In any case, on the two platforms, the process (low isolation level) is optimal. However, if the access rate is relatively low or the maximum throughput is low, the advantage of low isolation level is not obvious. Therefore, when each web server needs hundreds or thousands of pages per second, it is necessary to set the low isolation level. As usual, you should test a variety of configurations to determine which compromise you want to take. Note When you run an ASP process (intermediate or advanced isolation), they run in the MTS in NT4 and in COM in Windows 2000. That is, they run in MTX.exe in NT4; and in Windows 2000, they run in DLLHOST.exe. You can see these processes in the task manager. You can also see how IIS configure the MTS package or COM application for process ASP applications. The COM option has three configuration options, although it is not totally similar to the ASP option. The COM component can be "unconfigured", configured to library applications or configured as a server application. "Unconfigured" means that the component is not registered for COM . The component will run in the process space of the calling program, that is, they are "within the process." The library applicator is also within the process, but the service of COM includes security, transaction, and context support. Server applications are configured to run within their own process space. You can see that unconfigured components than library applications have some advantages. The library applicator is greater than the performance advantages of the server application. This is because the library applicator is running within the same process, while the server application runs in their own processes. The call between the processes is greater than the cost of calling in the process. Moreover, when data such as record sets is passed between processes, all data must be copied between two processes. trap! When you use a COM server application, if you pass an object between ASP and COM, make sure that the object performs "value collection" or MBV. Execute the object of MBV to copy themselves from a process to another process. This is good than one way. When using this method, the object is still in the creator's process, and the other process repeatedly calls the creation process to use the object. The cut-off ADO recordset will "collect the value collection", and the recorded record set is not. Scripting.dictionary does not perform MBV and is not passed between processes. Finally, VB programmers please note: MBV does not get through passing parameters Byval. MBV is executed by the author of the original component. How to do? If we recommend a reasonable configuration of performance and reliability, they should be as follows: In IS 4.0, use the ASP low isolation level to use the MTS server package. On IIS 5.0, the interval levels of the ASP are used and the COM library applicator is used. These are very general principles, and host service companies typically run the ASP in the middle or high isolation level, while single-use web servers can run at low isolation levels. Measure all kinds of advantages and disadvantages and decide which configuration is more in line with your needs. Tips 10: Use explicit options to use Option Explicit in .asp files. This instruction is placed on the top of the .asp file, and it enforces the developer to declare all the variables to be used. Many programmers believe that this method is very helpful for debugging applications, because this method avoids the possibility of key error variable name and misunderstanding new variables (for example, put myXmlstring =) is MYXLMSTRING = .... More importantly, the declared variable is faster than the unspeakable variable. Thus, the script is referenced by name each time the unspecified variable is running at runtime. On the other hand, the declared variables are sequentially or in compilation time or run time. Later, the declared variables are referenced in this order. Because Option Explicit mandatory variable declaration, it ensures that all variables are declared, so the speed of access is also very fast. Tips 11: Local variables using local variables in subroutines and functions are those variables declared within subroutines and functions. During the function or subroutine, local variable access is faster than global variables. The use of local variables will also make the code clearer, so local variables should be used. Tips 12: Copy the frequently used data to the script variable When accessing the COM object in the ASP, copy the object data that is often used is copied into the script variable. This can reduce the COM method call because the COM method call is relatively larger than the access script variable. This technique also reduces a lot of overhead looks when accessing the Collection and Dictionary objects. In general, if you plan to access object data at a time, the data should be placed in the script variable. This optimization is the REQUEST variable (Form and queryString variable). For example, your site can pass a querystring variable called UserID. Suppose this userid is referenced 12 times on a specific page. You may not need to call Request (? Userid?), But the UserID is assigned to a variable on the ASP page. This variable is then used at this page. This eliminates 11 COM method calls. In fact, it is not so big to access the COM attribute or method. Let's take an example to indicate a fairly common code (speaking from the grammatical): FOO.BAR.BLAH.BAZ = foo.bar.blah.qaz (1) if foo.bar.blah.zaq = foo.bar.blah.abc the '... When this code is running, the following is what happened: Variable FOO is parsed to a global object. Variable bar is parsed to members of FOO. This is actually a COM method call. The variable Blah is parsed to a member of foo.bar. This is another COM method call. Variable QAZ is parsed to members of foo.bar.blah. Nothing, this is still a COM method call. Call foo.bar.blah.quaz (1). Rethink again COM method call. understand? Steps 1 to 3 are performed again to parse BAZ. The system does not know whether to call QAZ to change the object model, so steps 1 to 3 must be performed again to parse BAZ. Parrse BAZ to a member of foo.bar.blah. Give properties. The steps 1 to 3 are performed again to parse ZAQ. Steps 1 to 3 are performed again to parse the ABC. As you can see, the efficiency is quite worse (and slow). The quick way to write this code with VBScript is: Set myobj = foo.bar.blah 'do the resolution of blah oncemyobj.baz = myobj.qaz (1) if myobj.zaq = myobj.abc dam ... If you use VBScript 5.0 or higher, you can use the with statement to write this code: WITH foo.bar.blah.baz = .qaz (1) if .zaq = .ABC THEN '... End with Note that this skill also applies to VB programming. Skills 13: Avoid re-determining the dimensions of the array should try to avoid the Redim array. In terms of performance, if the physical memory size of the computer is limited, it is best to set the initial dimension of the array to its most unfavorable case - or set the dimension to its best case, and then re-determine the dimension as needed. This does not mean that if you know that you don't need memory, you will always assign a few megabytes of memory. The following code shows you the case of improper use of DIM and Redim. <% Dim myarray (2) MyArray (0) =? Hello? Myarray (1) =? Good-bye? Myarray (2) =? FAREWELL? ... 'Some Other code where you end Up nexting more Space Happens, Then ... redim preserve myarray (5) MyArray (3) =? more stuff? myarray (4) =? Even more stuff? MyArray (5) =? YET MORE STUFF?%> It is best to start The initial size of the array DIM is correct (in this example, 5) makes it more better than the Redim array. You may waste some memory (if you don't use all the elements), the benefits of getting the speed becomes faster. Skill 14: Use the response buffer you can enable the "Response Buffer", a whole page to output. This will reduce the amount of the browser to minimize, thereby improving overall performance. Each write operation generates a large system overhead (in IIS, and in terms of data from the network), the less the write operation is, the better. Due to its slow start and use the Nagling algorithm (used to mitigate the network plucking condition), TCP / IP is much higher than the efficiency when sending some large data blocks. There are two ways to enable response buffering. The first, you can use Internet Services Manager to enable response buffering throughout the application. We recommend this method that enables response buffering to enable response buffering in IIS 4.0 and IIS 5.0. Second, the following code rows can be added to the top of each ASP page, thereby enabling a response buffer: <% Response.buffer = true%> This code must be performed before any response data is written to the browser (ie, before any HTML appears before the ASP script, and when any cookies is set to use the Response.cookies collection). In general, it is best to enable response buffering throughout the application. This way, you don't have to write the above-described code rows on each page. Response.flush has a common complaint about the response buffer, that is, the user feels that the ASP page is slow (even if the entire response time is improved), because they must wait until the entire page is generated, then they can see something. For pages long running time, you can set response.buffer = false, disable response buffering. However, a better strategy is to use the Response.flush method. This approach sent all HTMLs converted to the ASP to the browser. For example, after converting the first 100 rows of the 1,000 row, the ASP can call Response.flush to force the conversion to the browser so that the user can see the head 100 before the rest of the row. This technique can make the response buffer with the browser to make a perfect display of data. (Note that many browsers do not start the display before they see the TABLE> tag. Check if your target browser is supported. To avoid this, Multiple tables have fewer lines and call response.flush after each table. Newer version of Internet Explorer starts the display table before the table is completely downloaded, if you specify the lack of lack, the display speed will be particularly fast, This can avoid computing the Internet Explorer to calculate the column width by measuring the content width of each cell.) Another common complaint about response buffers is that many server memory will occupy a very large page. The method of generating a big page is not talked about, this problem can also be solved by cleverly using response.flush. Tips 15: Batch inline and response.write statement VBScript syntax <% = expression%> Write "Expression" to the ASP output stream. If the response buffer is not enabled, every statement is executed, and the data will be written to the browser with many small packets over the network. This speed is slow. Moreover, inserting a small amount of scripts and HTML will cause switching between script engines and HTML to reduce performance. Therefore, using the following tips: Use the Response.Write to call instead of bundled embedded expressions. For example, in the example below, each of the lines has a write operation on each line, and there is a number of switches between VBScript and HTML: The following code is more efficient, and each line has a write operation on the response stream. All code is included in a VBScript block: This technique is particularly large when the response buffer is disabled. Preferably, the response buffer is enabled, and then the batch response.write helps improve performance. (In this particular example, the nested cycle of the establishment of the form body can be replaced with a careful build GetString call.) Skill 16: If the page takes a long time to complete, use response.isclientConnected before execution If the user is in a hurry, they may give up the ASP page before you start to execute their requests. If they click refresh or move to another page on the server, there is a new request waiting at the end of the ASP request queue, and there is a disconnected request in the middle of the queue. When the server is loaded high (so the request queue will be long, the response time will become constant), which often happens, which can only make the situation worse. If the user is no longer connected, there is no meaning of the ASP page (especially slow, big ASP page). You can use the response.isclientConnected property to check this. If it returns false, response.end should call and discard the rest of the page. In fact, IIS 5.0 has compiled this practice as a program - whenever the ASP is about to perform new requests, it will check how long it has been waiting in the queue. If you have been waiting there for more than 3 seconds, the ASP will check if the client is still in connection. If there is no connection, the request is immediately terminated. You can use the ASPQUECONNECTIONTESTTIME setting in the configuration database to adjust the timeout from 3 seconds to other values. If the page spends for a long time to perform, you can also check Response.isclientConnected from time to time. When the response buffer is enabled, it is best to execute the response.flush from time to time, know what happens in the user. Note that in IIS 4.0, response.isclientConnected is not working properly unless the response.write is executed first. If buffer is enabled, you must also perform Response.flush. On IIS 5.0, it is not necessary to do this, - Response.isclientConnected is working properly. In any case, response.isclientConnected will have some overhead, so it is only a long time to spend 500 milliseconds in one operation (more than one-page throughput per second, this is a long time) Use it. Experience shows that do not call it while repeatedly performing a close cycle, such as many lines of displaying table - Calling once every twenty or 50 lines may be appropriate. Tips 17: Use the This is another example of an inertial calculation. Tips 18: Use the TypeLib declaration for ADO and other components When using ADO, developers often add Adovbs.txt to access various constants of ADO. This file must be included in each page to use constant. This constant file is quite large, adding a number of system overhead to the compilation time and script size of each ASP page. IIS 5.0 introduces features that bind to component type libraries. This allows you to reference the type library once and use it on each ASP page. Each page does not generate overhead of compiling constant files, and component developers do not have to build a VBScript # _include file to use on ASP. To access ADO Typelib, place the following statement in Global.asa. or Tips 19: Using the browser's verification function Today's browser provides support for some advanced features such as XML, DHTML, Java applets, and remote data services. Use these features as much as possible. All of these technologies can perform client-end verification and data caches, eliminating the round trip to the web server. If you are running a smart browser, the browser can verify you (for example, check if the credit card checksum is valid before performing POST). Use this feature as much as possible. By reducing the round trip between the customer-server, the load on the web server can be reduced, and network traffic (although the first page of the browser may be relatively large) and any backend resources accessed by the server. In addition, users don't have to read new pages like housing, so that users feel better. Don't mean that you can verify that server-side authentication is not performed. This prevents erroneous data from a client due to some reason (such as hackers, or browser without running client-side authentication routines). People have already conducted a lot of work and developed "independent browser" HTML. It is because of this concern, developers are reluctant to use popular browser features, but these functions can improve performance. For some real high-performance sites, you must care about the browser "Access" problem, a good policy is to optimize the page to adapt to the popular browser. Using the browser feature component, you can detect the browser function side in the ASP. Tools such as Microsoft FrontPage helps to design code suitable for browsers and specify HTML versions. See when is better worse? Weighing The Technology Trade-offs for further discussion. Skill 20: Avoid using a string in the cycle statement series to build a string in the loop statement, as shown below: S =? While Not Rs.eOfs = S & VBCRLF &? s = S & VBCRLF &? table>? & vbcrlfresponse.write s There are some problems in this way. The first question is that the time-string of the series string requires two times, more popular, running the time spending this loop statement and the number of records performed by the number of fields. For a simpler example, you can clearly explain this problem. s = ?? for i = ASC (? a?) to ASC (? z?) s = s & chr (i) Next In the first iteration, you get a string of characters? A ?. In the second iteration, VBScript must reassign strings and copy two characters (? AB?) To s. In the third iteration, it must also reassign S again and copy three characters to S. In n times (26th) iteration, it must be redistributed and copied n characters to S. The total is 1 2 3 ... N, namely n * (n 1) / 2 times. In the above recording set, if there are 100 records and 5 fields, the internal cycle will perform 100 * 5 = 500 times, all of the replication and re-allocation of time is proportional to 500 * 500 = 250,000. This is too much for the medium-sized recordset. In this example, the code can be improved by replacing the string series with a response.write () or embedded script (<% = fld.value%>). If the response buffer is enabled (it), this will be faster because response.write only attached the data to the end of the response buffer. It does not involve redistribution, so the efficiency is high. In a particular case of converting the ADO record set to an HTML table, you should consider using getRows or getString. If the string is used in JScript, it is especially recommended to use the = operator, ie, use S =? A string? Instead of S = S ? A string? Skill 21: Enable browser and proxy cache By default, ASP prohibits caching in your browser and proxy. This makes sense because the ASP page is dynamic, and there is a changing potential information over time. If the page does not require a refresh on each view, you should enable your browser and proxy cache. This allows the browser and agent to use the "Cache" copy of the page within a certain amount of time, you can control the length of time. The cache can greatly reduce the load on the server, shorten the wait time of the user. Which dynamic page can be used as a page to cache? Let's take some examples: Weather Forecast page, on this page, a weather forecast is updated every 5 minutes. List the homepage of news entries or press releases, it is updated twice a day. The common fund performance list, in which the basic statistics are updated every hour. Note that when using a browser or agency cache, the number of accesses recorded on the web server is reduced. If you want to accurately measure all page views or publish published, you don't want to use your browser and proxy cache. The browser cache is controlled by the HTTP "expired" header, which is sent by the web server to the browser. ASP provides two simple mechanisms to send this header. To set up the page, you should set the response.expires property when you expire it. The following example tells the browser to expire within 10 minutes: <% Response.expires = 10%> If you set the response.expires to a negative or 0, the cache is disabled. Be sure to use large negative numbers, such as -1000 (slightly more than one day) to avoid mismatch between servers and browser clocks. The second attribute response.expiresabsability will enable you to set the specific time of the content expired: <% response.expiresabsolute = #may 31,2001 13:30: 15 #%> You can use the Response object to set expiration time, and write the tag into the HTML, usually written in the Finally, you can use the Response.cacheControl property, indicating whether its content can make the HTTP proxy cache. If you set this property to "public", the agent can cache this. <% Response.cachecontrol =? Public?%> By default, this property is set to "Private". Note that for a page that displays a user-specific data, the proxy cache should not be enabled because the agent may give the user a page belonging to other users. Tip 22: Use Server.Transfer as much as possible to replace Response.Redirect Response.Redirect to let the browser request another page. This function is often used to redirect the user to a login or error page. Because the redirect enforcement request new page, the result is that the browser must go twice to the web server, and the web server must process a request. IIS 5.0 introduces a new function Server.Transfer, which will perform another ASP page on the same server. This avoids the round trip of excess browser -Web-servers, thereby improving overall system performance and shortening the user's response time. Check "New Direction" in "Redirect", which should be Server.Transfer and Server.execute. See also LeveRaging ASP IIS 5.0, understand the complete list of new features of IIS 5.0 and ASP 3.0. Tips 23: After using the slash in the directory URL, one-related tip is to ensure that the rear slash (/) is used in the URL pointing to the directory. If you have omitted the rear slash, the browser will send a request to the server, just to tell the server, it is in the request directory. The browser will issue a second request, attach the slash to the URL, only after this, the server can respond to the default document or directory list (if there is no default document and if the directory browsing is available). Additional slash can save the first, useless. To facilitate user reading, you can omit the rear bar in the name. For example, write: This also applies to URLs to the homepage on the web site: Use the following: , without using . Tips 24: Avoid using server variable access server variables to make a Web site a special request to the server, and collect all server variables, not just the variable you requested. This situation is similar to that in a moldy attic, find a file in a folder. When you want to find that file, you must go to the attic, first find the folder, and then find this file. When you request a server variable, the situation happens that the performance will be affected when you first request server variables. Requests to other server variables will not affect performance. Never access non-qualified REQUEST objects (for example, Request ("Data")). For items that are not in Request.Cookies, Request.Form, Request.QueryString, or Request.ClientCertificate, Request.ServerVariables implicitly. Request.ServerVariables collection is much slower than other collections. Tips 25: Upgrading to the latest and most excellent system components are constant, we recommend that you upgrade them to the latest and best configuration. It is best to upgrade to Windows 2000 (therefore, you should upgrade to IIS 5.0, ADO 2.5, MSXML 2.5, Internet Explorer 5.0, VBScript 5.1, and JScript 5.1). On multiprocessor computers, IIS 5.0 and ADO 2.5 can significantly improve performance. Under Windows 2000, ASP can extend well to four processors or more, and under IIS 4.0, the scalability of ASP cannot exceed two processors. The more the script code and ADO used in the application, the more performance improvements will be improved after upgrading to Windows 2000. If you can't upgrade to Windows 2000, you can upgrade to SQL Server, ADO, VBScript, and JScript, MSXML, Internet Explorer, and NT 4 Service Packs. They can improve performance and reliability. Tips 26: Optimizing the Web Server has a variety of IIS optimization parameters to improve site performance. For example, for IIS 4.0, we often find that increasing the ASP ProcessorthReadmax parameter (see IIS document) can significantly improve performance, especially in sites tend to wait for backend resources (such as databases) or other intermediate products (such as screen brush). In IIS 5.0, you may find that ASP Thread Gating is higher than finding an AspProcessorthReadmax optimal settings, which is now well known. For better reference materials, see Optimization IIS below. The best configuration setting depends on (some factors) application code, run the system hardware and client workload. The only way to find the best setting is to perform performance testing, which is what we have to discuss in the next trick. Tips 27: Performance Test As we have talked in front, performance is a feature. If you want to improve the performance of the site, then make a performance goal, then gradually improve until the target is reached. No, no performance test is performed. Typically, at the end of the project, the necessary structural adjustment is too late, your customers will be disappointed. Perform performance test as part of your daily test. Performance tests can be performed separately, such as for ASP pages or COM objects, or to test the site as a whole. Many people use a single browser request page to test the performance of the Web site. This will give you a feeling, that is, the responsive ability of the site is very good, but doing so actually can't tell you how the performance of the site under load conditions. Under normal circumstances, you need to accurately test performance, you need a dedicated test environment. This environment should include hardware, processor speed, processor number, memory, disk, network configuration, etc. similar to the hardware of the production environment. Second, you must specify the workload of the client: how many simultaneous users, they make the frequency of request, they click on the type of page, and so on. If you don't have data on site actual usage, you must estimate the situation used. Finally, you need a tool that can simulate the expected client workload. With these tools, you can start answering questions such as "If I have N simultaneous users, how many servers do you need?" You can also find the cause of the bottleneck and optimize in this goal. Some good Web load test tools are listed below. We specially recommend the Microsoft Web Application Stress (WAS) toolkit. WAS allows you to record test scripts, then simulate hundreds or thousands of users to access the web server. WAS reports a lot of statistics, including the number of requests, response time distribution, and error counts per second. WAS has a wealth of client interfaces and WEB-based interfaces, and the web interface allows you to do remote testing. Be sure to read IIS 5.0 Tuning Guide. Tips 28: Reading Resources Links The following is some excellent resource links related to performance. If you would like to know about information, please read developing scalable Web Applications. Resource optimization ASP script Optimize IIS ADO and SQL Server ASP components and thread models Dictionary component Session status Performance and scalability tool bibliography ASP Web site ASP style Xml Optimize ASP Scripts Developing Scalable Web Applications GOT Any Cache? Nancy Winnick Cluts Maximizing the Performance of Your Active Server Pages, Nancy Winnick Cluts 15 Seconds: Performance Section ENHANCING Performance in Asp - Part I, Wayne Plourde WHEN is better wor? Weighing the technology trade-offs, Nancy Winnick Cluts Speed and Optimization Resources, Charles Carroll Optimization IIS The ART AND SCIENCE OF Web Server Tuning with Internet Information SERVICES 5.0 Leveraging ASP IIS 5.0, J.d. Meier Tuning IIS 4.0 for High Volume Sites, Michael Stephenson Tuning Internet Information Server Performance, Mike Moore Navigating the maze of settings for web server performance optimization, todd wanke Managing Internet Information Server 4.0 for Performance, Hans Hugli ADO and SQL Server Top Ten Tips: Accessing Sql Through ADO and ASP, J.D. Meier Improve the Performance of Your MDAC Application, Suresh Kannan Pooling in the Microsoft Data Access Components, Leland Ahlbeck and Don Willits SQL Server: Performance Benchmarks and Guides Improving The Performance of Data Access Components with IIS 4.0, LELAND AHLBECK Microsoft Data Access Components (MDAC) And ActiveX Data Objects (ADO) Performance Tips, LELAND AHLBECK Microsoft SQL Server 7.0 Practical Performance Tuning and Optimization - The Server Perspective, Damien Lindauer Microsoft SQL Server 7.0 Practical Performance Tuning and Optimization - The Application Perspective, Damien Lindauer Accessing records over the internet, Dino Esposito ASP components and thread models ASP Component Guidelines, J.D. MEIER Q243548: Info: Design Guidelines for VB Components Under ASP Threading Models Explained, Nancy Winnick Cluts SO Happy TOGETHER? Using ActiveX Components with Active Server Pages, Nancy Winnick Cluts Developing Active Server Components with ATL, George Reilly Agility In Server Components, Neil Allain Building High-Performance Middle-Tier Components with C , Jon Flanders Active Server Pages and Com Apartments, DON BOX House of com: Active Server Pages, Don Box House of com: contexts, Don Box House of com: performance trade-offs of the windows 2000 company Component Design PrinciPles for MTS Dictionary component Creating a page cache object, Robert Coldidge Abridging The Dictionary Object: The ASP Team Creates a lookup-Table Object, Robert Carter Caprock Dictionary Site Server Commerce Edition Includes a Dictionary Component Session status Q175167: HOWTO: PERSISTING VALUES WITHOUT sessions Q157906: HOWTO: How to maintain State Across Pages with VBScript XML-Based Persistence Behaviors Fix Web Farm Headaches, Aaron Skonnard House of com: stateless programming, don box Performance and Scalability Blueprint for Building Web Sites Using The Microsoft Windows DNA Platform Server Performance and Scalability Killers, George Reilly Microsoft Visual Studio Scalability Center Fitch & Mather stocks 2000 TUNING THE FMSTOCKS APPLICATION High-Performance Visual Basic Apps, Ken Spencer Duwamish books, Phase 4 TOP Windows Dna Performance Mistakes and How To Prevent Them, Gary Geiger and Jon Pulsipher Building from static html to high-performance web-farms, Shawn Bice Tool Microsoft Web Application Stress Tool I can't stress it enough - loading test your asp application, j.d. Meier Windows DNA Performance Kit Monitoring Events in Distributed Applications Using Visual Studio Analyzer, Mai-Lan Tomsen Bibliography Professional Active Server Pages 3.0, Wrox Press (especially Chapter 26: Optimizing ASP Performance, George Reilly and Matthew Gibbs). Microsoft Internet Information Services 5.0 Resource Guide (with Windows 2000 Server Resource Kit), Microsoft Press. Microsoft Internet Information Server Resource Kit (for IIS 4.0), Microsoft Press. Programming Distributed Applications with Com and Microsoft Visual Basic 6.0, TED Pattison, Microsoft Press. Effective COM, DON BOX, Keith Brown, Tim Ewald and Chris Sells are incorporated by: Addison-Wesley. Developing Web Usability: The Practice of Simplicity, Jakob Nielsen, New Riders. ASP Web Site Microsoft TechNet for IIS Learnasp.com 4Guysfromrolla.com 15seconds.com AskODAY.com Ask101.com Asplists.com. Many professional mailing lists include: Fast Code! ASP Advanced Not Newbiestate Management Scalability Visual Basic Components XML C / ATL Component Building Useit.com: Web availability ASP style ASP BEST PRACTICES, George REILL ASP Quick Lessons, Charles Carroll Planning for ASP, John Meade ASP Guidelines, J.D. Meier XML INSIDE XML Performance, Chris Lovett Inside msxml3 performance, chris lovett <% for each fld in rs.fields%>
<% = fld.name%> tH> <% next while not rs.eof%> <% = fld.value%> td> <% next tr> <% rs.movenext wend%> table>
<% for Each Fld in rs.fieldsResponse.write (?
? & fld.name &? t>? & vbcrlf) NextWhile Not Rs.eOfResponse.write (? ?) for Each Fld in rs.fields%> Response.write (? ? & fld.value &? td>? & vbrlf) NextResponse.write? tr>? Wend%> Table>
? & vbrlfor Each fld in rs.fieldss = S &?
? & fld.name &? t>? Next
? For each fld in rsfieldss = s &? ? & Fld.value &? Td>? Nexts = s &? Tr> ? rs.movenextwend