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.
table of Contents
Tips 1: Cocaine the frequently used data on the web server 2: Cocaine frequently used in the application or session object 3: Cocard the data and HTML on disk on the web server 4: Avoid nonsense Components Cacked in Application or Session Objects 5: Do not use the database connection in Application or Session objects 6: Reasonably use session object skills 7: package code package in COM objects 8: Late get a resource, earlier Release Resource Skills 9: Process External Execution Process with Performance Change Reliability Tips 10: Using Explicit Options Tips 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 tip 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 < Object> Tag Example Object Skills 18: Use TypeLib Binding Tips for ADO and Other Components 19: Using Browser Verification Function Tips 20: Avoid using string tangible tricks in a loop statement 21: Enable browser and proxy cache skills 22: Use Server.Transfer instead of Response.Redirect Tips 23: Rear Slash Tips in Directory URL 24: Avoid Using Server Variable Tips 25: Upgrade to Latest and Experienced Tips 26: Optimizing Web Server Tips 27: Performance Test Tips 28: Reading resource links Introduction Performance is a feature. You must pre-design performance, otherwise you have to rewrite the application later. That is to say, what good strategies can make Active Server Pages (ASP) performance best? 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. For example: (?? EmploymentStatusList) (?? EmploymentStatusList) <% Function GetEmploymentStatusListDim dd = Application If d = ?? Then 'FetchEmploymentStatusList function (not shown)' fetches data from DB, returns an Arrayd = FetchEmploymentStatusList () Application = dEnd IfGetEmploymentStatusList = Dend function%> You can write a similar function for each data block you need. 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 generators using getRows () returns record set: 'get recordset, return as an arrayfunction fetchemploymentStatusListdim 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 Arrayrs.CloseSet rs = NothingEnd Function of The above example is further improved, and the HTML can be cached as a list instead of an array. The following is a simple example: 'Get Recordset, return as HTML Option listFunction FetchEmploymentStatusListDim rs, fldName, sSet rs = CreateObject rs.Open select StatusName, StatusID from EmployeeStatus ?, _ dsn = employees; uid (ADODB.Recordset??)?? = 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?) Ife (update_interval 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 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, Strov 'now disconnect the Recordset from the data provider and data sourcers.activeConnection = Nothing 'Step 2 For more details on the connection pool, you can find in the ADO and SQL Server reference. 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 the ASP by page-by-page, you no longer need the session object on this page, use the following on the ASP page top instruction: <% @ enablessionsState = false%> Have a good reason to use this instruction, these Session has a interesting issue 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 to 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 illustrate 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 THEN '... 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 overcemyobj.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 With Note this skill is also Suitable for 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, you can add the following line rows on the top of each ASP page, enabling response buffer: <% response.buffer = true%> This code must be performed before any response data is written to the browser (I.e., before any HTML appears before the ASP script, you can set any cookies before using 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, there is a write operation on each of each line of each line, and there is a number of switches between VBScript and HTML: 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 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. Tips 20: Avoid using a string in a cycle statement series to create a string in the loop statement, as shown below: s =? <% for each fld in xiLDS%> < TH> <% = fld.name%> th> <% next while not rs.eof%>
<% for each fld in xi = flds%> <% = fld.val%> < / TD> <% next tr> <% rs.movenext wend%> table> The following code is more efficient, each line has a write operation on the response stream. All code is included in a VBScript block: <% for each fld in rsfieldsresponse.write (? <" .Write (?
?) For Each Fld in rs.fields%> Response.write (? ? & Fld.value &? Td>? & Vbcrlf) NextResponse.write? Tr>? Wend%> TABLE> 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 nesting cycle of the establishment of the main body can be replaced with carefully build GetString calls.) Skill 16: If the page takes a long time to complete, then execute Before using response.isclientconnected, if the user is in a hurry, they will give up the ASP page before you start to perform their request. 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.