Introduction
Skill 1: Cache common data on the web server
Tip 2: Cache Common Data in Application or Session Objects
Tips 3: Cache data and HTML on web server disk
Tips 4: Avoid cache non-flexible components in Application or Session objects
Tips 5: Do not cache database connections in Application or Session objects
Skills 6: Wonderful session object
Tips 7: Package code in COM object
Tips 8: Late to get resources, release resources earlier
Skills 9: Execution outside the process will sacrifice reliability
Tips 10: Explicit use options
Tips 11: Use local variables in subroutines and functions
Tips 12: Copy common data to script variables
Tips 13: Avoid redefining arrays
Tips 14: Use response buffer
Tips 15: Batch in-embedded script and response.write statement
Tips 16: Use response.isclientConnected before starting a long time
Tips 17: Instantialective Objects using
Tips 18: Typelib binding using ADO objects and other components
Tips 19: Using the browser's verification capabilities
Tips 20: Avoid strings in the cycle
Tips 21: Enable browser and agent cache
Tips 22: Use Server.Transfer as much as possible to replace Response.Redirect
Tips 23: Directory URL tail plus slope
Tips 24: Avoid using server variables
-------------------------------------------------- ------------------------------
Introduction
Performance is a feature. You need to pre-design performance or rewrite the application in the future. In other words, what is a good policy for optimizing the Active Server Pages (ASP) application performance?
This article provides many techniques for optimizing the ASP application and the "Visual Basic (R) script editor (VBScript)". Discuss many traps and defects. The recommendations listed herein are
Testing on http://www.microsoft.com and other sites, and work is working. This article assumes that you have basic understandings for ASP development, including VBScript and / or JScript, ASP Application, ASP Session, and other ASP internal objects (requests, responses, and servers).
The performance of ASP, usually more than just depends on the ASP code itself. We don't want to cover all the names in an article, only listing resources related to performance. These links include ASP and non-ASP topics, including an "ActiveX (R) Data Object (ADO)," Part Object Model (COM) ", database, and Internet Information Server (IIS)" configuration. These are the links we like - please pay attention to them.
Skill 1: Cache common data on the web server
Typical ASP Pages Retrieve data from the backend database, and then convert the results to Hypertext Markup Language (HTML). Regardless of the speed of the database, it is much more fast from the memory retrieval data to retrieve data from the backend database. Reading data from local hard drives is usually more than retrieving data from a database. Therefore, performance can be improved by cache data on a web server (in memory or disk).
The cache is a trade-off of typical space and time. If you just caching data, you will see performance will have an amazing improvement. To make the cache effect, it must maintain frequently reused data, and the cost of recalculating these data is expensive or expensive. If the cache is full of spam, it is a waste of memory. Data that do not change often is also a cached candidate data because you don't have to worry about data and database synchronization issues. Combination box, reference table, DHTML debris, scalable markup language (XML) string, menu item, and site configuration variable (including data source name (DSN), Internet Protocol (IP) address, and web paths) are candidate data. . Note that you can cache data indicating instead of the data itself. If the ASP page does not change frequently, and the cost of the cache is also very high (for example, the entire product catalog), consider the first HTML, rather than re-drawing each time.
Where should data should have, what caching strategies? Data often buys on the web server memory or web server disk. The following two techniques discuss these options.
Tip 2: Cache Common Data in Application or Session Objects
The ASP Application and Session objects provide a convenient container for cache data in memory. You can give the Application object or give the data object to the SESSION object, which will remain in the memory in the HTTP call. The session data is stored by user, and the Application data is shared between all users.
When will I load the data into the Application or Session? Typically, load data when the Application or Session starts. To load data at the Application or Session startup, add the corresponding code in the two functions:
Application_onstart ()
or
Session_onstart ()
. These two functions should be in Global.asa; if not, these functions can be added. You can also load data when data is required for the first time. To make the above, add some code (or write a reusable scripting function), which checks the data in the data and loads data when the data does not exist. This is an example called a classic performance technology called slow-calculated - not calculated before you need it. Please see example:
<%
Function geteMPloymentStatusList
DIM D
D = Application ("EMPLOYMENTSTATUSLIST")
IF d = "" "
'Fetchemploymentstatuslist function (not displayed)
'Take data from DB, return array
D = fetchemploymentstatuslist ()
Application ("EMPLOYMENTSTATUSLIST") = D
END IF
GetEmploymentStatusList = D
END FUNCTION
%>
Similar functions can be written for each piece of data required.
What format should be stored in any format? Any variable type can be stored because all script variables are different. For example, you can store strings, integer or arrays. Typically, you will save the contents of the ADO record set in one of these variable types. To get the data derived by the ADO recordset, you can manually copy the data into the VBScript variable, each time a field. Use an ADO recordset reserved function getRows (), getString () or Save () (ADO 2.5), which will be faster. Complete and detailed content has exceeded the scope of this article. The following demo function uses getRows ()
To return to the array of record set data:
'Take a record set, return to the array
Function FetChemploymentStatusList
DIM RS
SET RS = CreateObject ("AdoDb.Recordset")
Rs.open "Select StatusName, Statusid from Employeestatus", _
"DSN = Employees; UID = SA; PWD =;"
FetChemploymentStatusList = rs.getrows () 'Returns data in an array
Rs.close
SET RS = Nothing
END FUNCTION
Further improvements to the above example should be HTML of the list instead of cache an array. Here is a simple example:
'Take a record set, return to the "HTML Options" list
Function FetChemploymentStatusList
DIM RS, FLDNAME, S
SET RS = CreateObject ("AdoDb.Recordset")
Rs.open "Select StatusName, Statusid from Employeestatus", _
"DSN = Employees; UID = SA; PWD =;"
S = "
Set fldname = rs.fields ("statusname") 'ADO field binding
Do Until Rs.eof
'The following lines violate the string connection,
'But this is ok because we are building caches.
S = S & "
rs.movenext
Loop
S = S & " SELECT> & VBCRLF
Rs.close
Set rs = nothing 'See Al released as soon as possible
FetChemploymentStatusList = s' returns data in strings
END FUNCTION
In normal case, cache the ADO recordset itself in the Application or Session scope. There are two warnings:
ADO must be labeled free thread
A disconnected recordset must be used.
If you cannot guarantee these two requirements, please don't cache the ADO record set. In the following non-flexible components and do not cache connection skills, we will discuss the risk of storing COM objects in the Application or Session scope.
If you store data in the Application or Session scope, these data will remain there until it changes it in the program, the Session expires or the web application is restarted. How does data need to be updated? To use manual to update the application data, you can call only data update ASP pages that allow administrators to access. In addition, data can be automatically refreshed through a function, periodically. The following example stores a timestamp with cache data, refreshing data after the specified time interval. <%
'No error handling ...
Const update_interval = 300 'Refresh Time Interval, in seconds
'Function Returns the list of hired status
Function geteMPloymentStatusList
UpdateemPloymentStatus
GetEmploymentStatusList = Application ("EmploymentStatusList")
END FUNCTION
'Regular update cache data
Sub UpdateEmploymentStatusList
DIM D, STRLASTUPDATE
StrlastUpdate = Application ("Lastupdate")
IF (strlastupdate = ") or _
(Update_Interval Datediff ("S", STRLASTUPDATE, NOW) THEN
'Note: There may be two or more calls here. This is ok, just
'Generate a few unnecessary referentials (there is a work area)
'Fetchemploymentstatuslist function (not displayed)
'Take data from DB, return an array
D = fetchemploymentstatuslist ()
'Update Application objects. Application.lock ()
'To ensure consistent data
Application.lock
Application ("EMPLOYMENTSTATUSLIST") = D
Application ("Lastupdate") = CSTR (now)
Application.unlock
END IF
End Sub
Other examples, see the fastest list box with Application data (English).
Note that a large array is not a policy in the session or Application object. Before accessing array elements, the syntax required for scripting languages requires temporary copies of the entire array. For example, if you cache the array of strings that map the US Zip Codes to the local weather station in the Application object, the array array has 100,000 elements. Before finding a string, you must copy all 100,000 weather stations to Temporary array. In this case, a custom component with a custom method is established to store weather stations - or use a dictionary component, perhaps better.
Please don't pour your child together when you take a bath, a new annotation for this view is that the array provides quick look and storage of adjacent critical-data pairs in memory. The index dictionary bit is slower. You should choose the data structure that provides the best performance according to the specific situation.
Tips 3: Cache data and HTML on web server disk
Sometimes, excessive data cannot be cached in memory. "Excessive" is a qualitative judgment; it depends on the amount of memory intended, and has the number of cache items and the retrieval frequency of these items. In short, if there are too many data to cache in memory, consider cache data on the web server's hard drive in the form of text or XML files. The data can be combined on the disk and the cache data is combined in memory, and the optimal cache policy is established for the site. Note that when the performance of a single ASP page, retrieving data on the disk is not necessarily faster than retrieving data from the database. However, the cache reduces the load of the database and the network. In high-load conditions, this will significantly improve overall traffic. When the query cost is high, the result of the caching query is very valid, such as multi-table combined or complex stored procedures, or cache large-scale result sets. Test competition programs in accordance with conventions.
ASP and COM provide several tools to build disk cache schemes. The Save () and Open () functions of the ADO record set, save and load the record set on the disk. You can use these methods to override the sample code in the Application Data Cache Tip, replace the code to write data to the Application object with the save () file.
There are other components that handle files:
Scripting.FileSystemObject enables you to create, read, and write files.
MSXML is the Microsoft (R) XML parser provided with Internet Explorer, which supports saving and loading an XML document.
The Lookuptable object (an example used on the MSN) is a good choice for loading a simple list from the disk.
Finally, consider cache data on disk, not the data itself. Prefably html can be stored as a .htm or .asp file on disk; hyperlink can directly point to these files. Using a commercial tool, such as XBuilder or Microsoft (R) SQL Server's Internet distribution function comes from the HTML generation process. Alternatively, the HTML fragment can be included in the .asp file. You can also read the HTML file from the disk using FileSystemObject or use XML for early adjustment (English).
Tips 4: Avoid cache non-flexible components in Application or Session objects
Although cache data in Application or Session object is a good idea, caching COM objects may have serious defects. Embed common COM objects to Application or session objects is usually attractive. Unfortunately, a lot of COM objects, including COM objects written in Visual Basic 6.0 or earlier, which will cause serious bottlenecks when storing in Application or Session objects.
Especially any non-flexible components, the performance bottleneck will result in a SESSION or Application object. Flexible components are marked as
ThreadingModel = Both
Components (it aggregates the free thread collector (ftm)) or marked as
ThreadingModel = neutral
Components (Windows (R) 2000 and new "neutral" models in COM .) The following components are non-flexible:
Free thread assembly (unless they gather FTM).
Unit thread components.
Single threaded components.
The configured component (MTS) / COM library, and server package / application) is non-flexible components unless they are "neutral" threads. Unit thread components and other non-flexible components are best suited to work in page scopes (that is, they are created and destroyed on a single ASP page). In IIS 4.0, labeled
ThreadingModel = Both
Components are considered flexible. This is not enough in IIS 5.0. Components must not only mark BOTH, but also to aggregate FTM. Flexible article explains how to get FTM with the C component written with "Activity Template Library". Note that if the component caching the interface pointer, these pointers themselves must be flexible or must be stored in the COM Global Interface Table (GIT). If you cannot recompile the Both thread component, you can get the FTM, you can mark the component as
ThreadingModel = neutral
. In addition, if IIS is not desired to be flexible (this, it is desirable that the non-flexible components can be stored in the Application or Session scope), which can be set in Metabase.
AsptrackthreadingModel
for
True
. Do not advocate changes
AsptrackthreadingModel
.
If you try to store in the Application object
Server.createObject
Unconventional components created, IIS 5.0 will generate errors. Can be used in Global.asa
Solve this problem, but does not advocate this, because this will result in aggregation and serialization, as follows.
What happened if the cache is non-flexible? Currently in the Sension object, the session "is locked" to an ASP grunger thread. ASP maintains a work controller thread pool that serves the request. Typically, new requests are processed by the first available worker thread. If the session is locked to a thread, the request will have to wait for the thread it associated to become available. For an example: You entered a supermarket, picking some food, and then pay the payment at No. 3. Since then, whenever you buy food in this supermarket, you have to pay the payment of the payment station on this supermarket, even if you have less or no one in other receiving tables.
Storing non-flexible components in the Applicaton scope or even a more serious impact on performance. The ASP will have to create a dedicated thread to run the components within the APPLICATON scope. This will result in two consequences: all calls have to be collected to the thread, and all calls are serially connected. Collection means that the parameters have to be stored in the memory shared area; perform expensive context switching for this dedicated thread; the method of the component is executed; the results are collected into the shared area; and after another expensive context switch, return control to the original the rout. Serialization means that all methods must run one manner (one method can only run at the same time). Two different ASP grid threads cannot perform methods on shared components simultaneously. This will kill parallel mechanisms, especially on multiprocessor computers. Dorse, all components in all non-flexible, Application scope will share a thread ("Host STA"), so serialization is more serious.
Are you confused? Below we have proposed a few general rules. If you are writing objects with Visual Basic (6.0) or earlier, do not cache them in Application or Session objects. If you don't know the object's thread model, don't cache it. Do not cache non-flexible objects, but to create and release them on each page. The object will run directly on the ASP grid thread so that you will not collect or serialize. If the COM object is running in the IIS box, and if they don't spend a long time, the performance will be sufficient. Note that do not use the single-threaded object with this method. CAUTION: VB can create a single-threaded object! If you have to use a single-threaded object (such as Microsoft Excel spreadsheet) in this way, you don't expect to have high throughput. When the ADO is marked as a free thread, the cache ADO recordset is safe. To mark the ADO as a free thread, use the Makfre15.bat file, which is usually located in the following directory: // Program Files / Common / System / ADO.
Warning: If you are using Microsoft Access as a database, you should not mark the ADO as a free thread. Typically, the ADO record set must also be disconnected if you cannot control the ADO configuration of the site (for example, you are independent software vendor [isv], sell web applications to customers, then manage their own Configuration), then the cached record set may be better.
Dictionary components are also flexible objects. LOOKUPTABLE loads its data from the data file and it is useful for combined box data and configuration information. PageCache objects from Duwamish books provide directory semantics, just as the performance of Caprock Dictionary. These objects or their derived objects can constitute the basis of a valid caching policy. Note that the scripting.dictionary object is not flexible, so it is not stored in the Application or Session scope.
Tips 5: Do not cache database connections in Application or Session objects
Cache ADO connection is usually a bad policy. If a Connection object is stored in the Application and is used on all pages, then all pages will compete with this connection. If the Connection object is stored in the ASP SESSION object, you will create a database connection for each user. This is destroyed by the benefits of the connection pool and generates unnecessary pressure on the web server and database.
The method of replacing the cache database connection is to create and cancel the ADO object on each ASP page using ADO. This is an effective way because IIS has a built-in database connection pool. More accurately, IIS automatically enables OLEDB and ODBC connection pools. This ensures that the connections created and canceled on each page will be valid.
Since a reference to a database connection is stored in a set of records, the connected recordset should not be cached in the Application or Session object. However, the disconnected recording set can be safely cached because it does not include references to their data connections. To disconnect the record, do the following two steps:
SET RS = Server.createObject ("AdoDb.Recordset")
rs.cursorlocation = aduseclient 'Step 1
'Recording set of data with data
RS.Open StrQuery, STRPROV
'Now disconnect the record set the integration data provider and the data source connection rs.activeConnection = Nothing' Step 2
For more information on connecting pools, see ADO and SQL Server (English) references.
Skills 6: Wonderful session object
After affirming the advantages of Cache in Applications and Sessions, we recommend that you avoid using the Session object. Here will be discussed, when used for busy sites, Sessions has several disadvantages. The so-called busy, usually refers to the request for hundreds of sheets per second or thousands of users at the same time. This technique is more important for sites that must be extended, that is, those sites that use multiple servers to accommodate load or perform fault tolerance. For smaller sites, such as intranet sites, SESSIONS is convenient, it is also worth it compared to overhead.
For refurbishment, the ASP automatically creates a session for users accessing the web server. Each session has approximately 10 kB of memory overhead (which is the highest in any data stored in the session) and makes all the requests. Session has been active until the configurable timeout (usually 20 minutes) is reached.
The biggest problem in Session is not performance but scalability. Session cannot span the web server; once it creates session on a server, its data remains there. This means that if you use sessions in the web domain, you will have to design a policy for each user's request to always lead these requests to the server's server. This is called the user "stick" to the web server. The term "viscous session" comes from this. Since the session is not kept on the disk, the user who is "sticky" will lose their sessions when the web server crashes.
Strategies for implementing viscous sessions include hardware and software solutions. For example, network load balancing solutions in Windows 2000 Advanced Server and Cisco's Local Director library can implement a viscous session, but at the expense of some scalability. These solutions are not perfect. We don't advocate you overthrown your software solution (we have used the ISAPI filter and URL straightening).
Application objects cannot span the server; if you need to share and update Application data in the web domain, you need to use the backend database. But read-only Application data is still useful in the Web field.
If you just add normal runtime (for handling failover and server maintenance), most of the implementation of important tasks will need to deploy at least two web servers. So, when designing an application for important tasks, you will need to implement "viscous sessions" or simply avoid SESSIONS and other status management techniques that store user status on a single web server.
If you are currently not using sessions, make sure they are turned off. You can perform this action for your application via "Internet Service Manager" (see ISM document). If you decide to use Sessions, you can take several methods to reduce the impact of performance to minimize.
You can move content that you don't need sessions (such as "Help" screen, visitors, etc.) to close SESSIONS, separate ASP applications. You can prompt page by page sheet: You don't need a session object in a given page; use the following instructions located at the top of the ASP page: <% @ enablessionState = false%>
A good reason to use this instruction is that session brings an interesting question to the frameset. ASP guarantees only one request from Session at any time. This ensures that if the browser requests multiple pages for a user, only one ASP request will enter session; this avoids multithreading problems when accessing the session object. Unfortunately, as a result, all the pages in the frameset are drawn in a serialized manner, one connection one, not simultaneously. In this way, users may have to wait for a long time to get all frame contents. This means: If some framepages do not trust Session, be sure to use
@ EnablesessionState = false
The instruction tells the ASP.
As an alternative to the session object, there are many ways to manage the SESSION state. For conditions (less than 4 KB), the number of states (less than 4 KB) is often recommended using a cookies, queryString variables, and hidden variables. For larger numbers of data, such as shopping carts, use backend databases is the most appropriate selection. There are many data on state management technology in the web server field. For more information, see the Session Status (English).
Tips 7: Package code in COM object
If you have a lot of VBScript or JScript, you can improve their performance by moving the code to the compiled COM object. Compiled code is usually more running faster than interpreted code. Compiled COM objects can access other COM objects with Early Binding, this means of calling the COM object method, which is more effective than the "post binding" used by the script.
Package the code in the COM object has the following benefits (transcendence):
The COM object is a good way to break the expression logic with business logic.
The COM object enables the code reuse.
Many developers have found that using the code written by VB, C or Visual J , which is more easily debugged than the ASP.
COM objects have some shortcomings, including initial development time, and requires different programming skills. You need to warn that you are "less" amount of ASP in encapsulation may result in performance reduction, not improved. Typically, such a situation occurs when a small ASP code is encapsulated into a COM object. At this time, create and call the overhead of the COM object, exceeding the benefits of compiled code. As for how the ASP script and COM object code merge can generate optimum performance to be tested. Note that Microsoft has greatly improved scripting and ADO performance in Windows 2000 / IIS 5.0 compared to Windows NT (R) 4.0 / IIS 4.0. Thus, the performance advantage of the compiled code to the ASP code has decreased with the introduction of IIS 5.0.
For more discussion on the advantages and disadvantages of using COM objects in ASP, see Programming Distributed Applications with COM and Microsoft Visual Basic 6.0 (English). It is very important if you are deployed in COM components. In fact, all ASP applications should be intensive as a formal process. Tips 8: Late to get resources, release resources earlier
This is a tip. Usually, it is best to get resources later and release resources earlier. These resources include COM objects, file handles, and other resources.
The ADO connection and record set are the primary goal of this optimization. When you use the recordset, just print a form with its data, please release it immediately, not the end of the page. Set your VBScript variable to
Nothing
It is the best practice. Do not let the record set simply detach the scope. At the same time, any relevant Command or Connection object should be released. (Don't forget to call the record set or "connection"
Close ()
, Set them to
= Nothing
prior to. This will shorten the database must adjust the resource time span and release database connections as quickly as possible to the connection pool.
Skills 9: Execution outside the process will sacrifice reliability
ASP and MTS / COM have access to performance options for performance in reliability. This exchange should be understood when establishing and deploying an application.
ASP option
The ASP application can be configured to operate in one of three ways. The term "isolation level" is introduced in IIS 5.0 to describe these options. The three isolation levels are low, medium and high:
Low level isolation. This isolation level is supported in all version of IIS and is the fastest. It performs ASP in the primary IIS process in inetinfo.exe. If the ASP application crashes, IIS will also crash. (To restart IIS in IIS 4.0, the Web site administrator needs to use tools, such as inetmon, to monitor site, if the server fails, run the batch file to restart the server. And IIS 5.0 introduces reliable restart, It will automatically restart the failed server.)
Intermediate isolation. IIS 5.0 introduces this new isolation level, which is called processes because ASP is running outside the IIS process. In intermediate isolation, all ASP applications that are configured as "intermediate" run will share the single process space. This will reduce the number of processes needed to run the ASP application outside of a server running multiple processes. Intermediate is the default isolation level in IIS 5.0.
Advanced isolation. Supported in IIS 4.0 and IIS 5.0, and advanced isolation is also outside processes. If the ASP crashes, the web server does not collapse. The ASP application will automatically restart when the next ASP request is requested. With advanced isolation, each ASP application that is configured to run is run in its own process space. This protects the ASP applications from interference from each other. Its disadvantage is that it needs to establish an independent process for each ASP application. When you need to host more than ten applications on a server, you will add a lot of overhead.
So, which option is best? In IIS 4.0, the application outside the process will greatly affect performance. In IIS 5.0, many work has been made so that the process running ASP applications to performance has fallen to the lowest. In fact, in most tests, an ASP process applied in IIS 5.0 is run faster than in the process in IIS 4.0. In any case, there is still the best performance in the process (low isolation level) in both platforms. However, if your hit rate is relatively low or the maximum throughput is low, you will choose a low isolation level. So, unless you need to process hundreds or thousands of pages per second per second, there is no need to select a low isolation level. Similarly, you should test a variety of configurations and judgment which situation is best for you. Note: When you run an ASP application (intermediate or advanced isolation), they will run in the MTS on NT4, and they will run in COM on Windows 2000. That is, they run in MTX.exe on NT4, and they run in DLLHOST.EXE on Windows 2000. In Task Manager, you can see these running processes. You can also see how IIS configure the MTS package or COM application for ASP applications outside the process.
COM option
There are three configuration options that COM components, although it is not completely similar to the ASP option. The COM component can be: "Not Configure", configured to "library applications" or configured as "server application". "Not configured" means that it is not to the COM registration component. The component will run in the caller's process space, that is, they are "in the process". "Library Applications" is also in the process, but benefit from COM services, including security, transaction, and environmental support. "Server Application" is configured to run in its own process space.
You may see that the unconfigured component ratio is slightly more. You may also see that "library applications" is a great performance advantage than "server applications". This is because "library applications" and ASP run in the same process, and "server applications" run in their own process. The overhead of internal process calls is much larger than the overhead calls within the process. Moreover, when data (such as a recordset) is transmitted between the process, you must copy all the data between the two processes.
Disadvantage! When using the COM Server Application, if you want to transfer an object between ASP and COM, make sure that the object is "Collection," MBV. Implementing the MBV object to copy itself from a process to another process. This is better than another, in another way, the object is left in the process of creating it, while other processes repeat the process of creating the use of the object. The ADO recordset that is disconnected will be collected, and the connected records that have been connected are not. Scripting.dictionary does not implement MBV and will not be passed between processes. Finally, to tell the VB programmer: MBV is not passing parameters
BYVAL
acquired. MBV is implemented by the original component creator.
How to do?
If you want to complete your configuration with reasonable exchange of performance and reliability, our recommendation is as follows:
On IIS 4.0, use the low isolation level of ASP and use "MTS Server Pack".
On IIS 5.0, use ASP's neutralization level and use "COM library applications". These are general guidelines; usually operate the ASP in the middle or high isolation level, while a single purpose Web server can run at low isolation levels. Please emphasize and determine the configuration of the demand.
Tips 10: Explicit use options
Explicitly used in .asp files
Option EXPLICIT
. This instruction set at the .asp file, forced the developer to declare all the variables to be used. Many developers believe that this helps to debug applications because it avoids new variables that do not deliberately enter the variable name (for example,
Myxlmstring = ...
Not
MyXmlstring =)
.
Perhaps more importantly, the declared variable is faster than the unspeakable variable. In fact, when the script is run, you will be referenced by name when using an undeclared variable. The declared variables are allocated in compilation or runtime. In this way, the declared variables are referenced in accordance with the serial number. due to
Option EXPLICIT
Forced variable declarations, so that all variables are guaranteed to achieve quick access.
Tips 11: Use local variables in subroutines and functions
Local variables are variables declared in subroutines and functions. In subroutines and functions, local variable access is faster than global variables. Using local variables can also make the code clearer, so use local variables as much as possible.
Tips 12: Copy common data to script variables
When you access your COM in the ASP, the commonly used object data should be copied into the script variable. This will cut the call of the COM method, and the call of the COM method is relatively expensive than access script variables. This technology can also cut expensive lookups when accessing the Collection and Dictionary objects.
Typically, if you intend to access object data multiple times, place the data into the script variable. The main objective of this optimization is the Request variable (Form and queryString variable). For example, your site may pass a querystring called Userid. Assume that the UserID variable is to reference 12 times in a specific page. Please do not call
Request ("UserID")
12 times, and the UserId is given a variable at the beginning of the ASP page. Then use this variable on the page. This will save 11 COM methods calls.
In practice, access COM properties or methods hide the complicated process and a lot of overhead. Here is an example, it is just a quite common code (from the grammar):
FOO.BAR.BLAH.BAZ = foo.bar.blah.qaz (1)
If foo.bar.blah.zaq = foo.bar.blah.abc then '...
The following events will occur when running this code:
variable
Foo
The resolved is global variable.
variable
Bar
Parsed
Foo.
the member of. This will produce a COM method call.
variable
Blah
Parsed
FOO.BAR
the member of. This will also produce COM method calls.
variable
QAZ
Parsed
FOO.BAR.BLAH
the member of. Yes, this will also produce a COM method call.
transfer
FOO.BAR.BLAH.quaz (1)
. Another COM method is generated again. Understand this picture?
Executive steps 1 to 3 will resolve again
BAZ
. System does not know call
QAZ
Whether to change the object model, so step 1 to 3 must perform resolution again
BAZ
.
will
BAZ
Analyze
FOO.BAR.BLAH
the member of. Perform attributes.
Step 1 to 3 again and resolve
ZAQ
.
Step 1 to 3 again and resolve
ABC
.
As you see, this is very terrible low efficiency (and very slow). The quick way to write this code with VBScript is: set myobj = foo.bar.blah 'a resolution to Blah
Myobj.baz = myobj.qaz (1)
If myobj.zaq = myobj.abc then '...
If you are using VBScript 5.0 or higher, you can use
WITH
The statement is written to this code:
With foo.bar.blah
.baz = .qaz (1)
If.zaq = .abc dam ...
...
End with
Please note that this technique is equally valid for VB programming.
Tips 13: Avoid redefining arrays
try to avoid
Redim
Array. From the perspective of careful performance, if the computer is limited by physical memory, it is best to set the dimension of the array to the worst scheme. Not to set the dimension to the best solution, and then redefine the dimension as needed. This doesn't mean that you don't need so much, you should allocate too much memory.
The following code shows that you don't have to use it.
DIM
with
Redim
To solve.
<%
DIM myArray ()
Redim MyArray (2)
MyArray (0) = "Hello"
MyArray (1) = "Good-bye"
MyArray (2) = "FAREWELL"
...
'Some other codes, here you don't need more space, then ...
Redim Preserve MyArray (5)
MyArray (3) = "more stuff"
MyArray (4) = "Even more stuff"
MyArray (5) = "yet more stuff"
%>
Better way is to only be started
DIM
The array is the correct size (5) in this case, not
Redim
Array, increase arrays. This may waste a little memory (if all elements are not exhausted), it is the speed.
Tips 14: Use response buffer
You can buffer the entire page worth output by opening the Response Buffer. This will reduce the amount of data written to the browser to minimize, thereby increasing overall performance. There will be a lot of overhead each time, including IIS and the amount of data sent through the cable), the less the write is, the better. The work efficiency of TCP / IP is significantly higher than when sending a small amount of data blocks. The reason is due to its low speed start and Nagling algorithm (for minimizing network blocking).
There are two ways to open the response buffer. The first, you can use the Internet Service Manager to open the response buffer throughout the application. This is a recommended approach, in IIS 4.0 and IIS 5.0, by default, the response buffer is opened for the new ASP application. Second, put the following code on the beginning of the ASP page, enable response buffer:
<% Response.buffer = true%>
The line code must be executed before any response data is written to the browser (that is, before any HTML appears in the ASP script, and any cookies is used.
Response.cookies
Before the set settings). Typically, it is best to open the response buffer throughout the application. This allows you to omit the lines of code in each page above.
Response.flush
In response to buffer is the user feels slow (although the overall response time is improved), because they need to wait until the entire page can only see this page. For long-running pages, you can set response.buffer = false
Close the response buffer. However, a better strategy is to use
Response.flush
method. This method refreshes all HTMLs plotted from the ASP into the browser. For example, the ASP can be called after 100 lines of 1,000 rows of tables.
Response.flush
Forced to draw the results to your browser; this allows users to see the head 100 line before preparing for the rest. This technology gives you two worldless good things - a combination of step-by-step display of data in the browser.
(Note, in the example of the 1,000 row, many browsers do not start drawing the table before seeing table> ending the tag. Please check the support of the target browser. To resolve this problem, please segment the table To have a plurality of tables with less line, then call after each table
Response.flush
. The new version of Internet Explorer will draw tables before the table is completely downloaded, especially if the column width of the specified table is faster; this avoids compulsory Internet Explorer to calculate the column width by metrics through the content of each cell. )
Another trick of the response buffer is a large amount of memory using the server when generating a large page. For this problem, in addition to the skill of generating large-scale page, you can also use it.
Response.flush
To solve.
Tips 15: Batch in-embedded script and response.write statement
VBScript syntax
<% = expression%>
will"
expression
"The value is written to the ASP output stream. If the response buffer is not open, each sentence of these statements will cause the browser to write data through the network, in the form of many small packages. This is very slow. In addition, explain a small amount Scripts and HTML will result in switching between scripting engines and HTML, which also reduces performance. So, please use the following tips: use
Response.write
One call, replace the in-intensive combination expression. For example, in the following example, each field has a write to the response stream, each row has a number of VBScript and HTML switching:
<% = fld.name%> tH>
<% NEXT While Not Rs.eof %> | ||||
---|---|---|---|---|
<% = fld.value%> td>
<% Next TR> <% rs.movenext Wend%> TABLE> The following is a more effective code, and there is a write in each row. All code is included in a VBScript block:
|