22 Tips for improving ASP performance (i)

Source: Internet
Author: User
Tags format array arrays functions variables string split variable
Skills | performance

  Tip 1: Cache common data on the Web server side

Most ASP pages have to extract data from the background database and then display the data in HTML format.
No matter how fast your database is, extracting data from memory is faster than extracting it from the background database, and reading data from your local hard disk is usually faster than from the database. Therefore, you can improve performance by caching data on the Web server side.

Caching is a typical transaction in which space is exchanged for time. If you cache the data correctly, performance may go by leaps and bounds. In order for a cache to be truly effective, you must buffer those commonly used and computationally complex data. Buffers that fill expired data can only waste memory.

Infrequently changing data is also a good candidate for caching because you don't have to be concerned with keeping the data in sync with the database. Drop-down list boxes, reference tables, small pieces of DHTML code, XML strings, menu items, and site configuration variables, including data source names (DSNs), IP addresses, and web paths, are good candidates for caching. Note that not only can you cache the data itself, but you can also cache the performance of the data. If an ASP page changes infrequently and the cache costs are higher (for example, a product list), consider using a static HTML page.

  Tip 2: Cache common data with application objects or session objects

ASP's application and Session object is an extremely convenient container for caching data in memory. You can put data into a application or Session object that will persist throughout the HTTP call. Each user has data from their own session object, and the data in the Application object can be shared among all users.

When should the data be loaded into the application or session? Typically, data is loaded when the application or session is started. To mount the data when the application or session is started, you need to add the appropriate code in Global.asa's Application_OnStart () or Session_OnStart () respectively If you do not have these two functions in Global.asa, you can add them manually. It can also be loaded when the data is first used. To do this, you should write some code (or write a reusable script function) on the ASP page to check for the existence of the data and load it into memory if the data does not exist. The following is a classic performance tuning technology--lazy evaluation:

<%
Function getemploymentstatuslist
Dim D
D = Application ("Employmentstatuslist")
If d = "" Then
' Fetchemploymentstatuslist function (not shown)
' Fetches data from DB, returns an Array
D = fetchemploymentstatuslist ()
Application ("employmentstatuslist") = d
End If
Getemploymentstatuslist = d
End Function
%>

Similar functions could is written for each chunk of data needed.

In what format should the data is stored? Any variant type can
stored, since all script variables are variants. For instance
can store strings, integers, or arrays. Often, you'll be storing the
Contents of an ADO recordset in one of these variable types. To get
Data out of a ADO recordset, can manually copy the data into
VBScript variables, one field at a time. It ' s faster and easier to
Use one of the ADO recordset persistence functions GetRows (), GetString
() or Save () (ADO 2.5). Full details are beyond the scope of this
Article, but here's a function that demonstrates the using GetRows () to
Return an array of recordset data:

' Get recordset, return 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 the recordset with an array
Rs. Close
Set rs = Nothing
End Function

A further refinement of the above might is to cache the HTML for the
list, rather than the array. Here's a simple sample:

' Get the Recordset, return the HTML option list
Function fetchemploymentstatuslist
Dim RS, Fldname, S
Set rs = CreateObject ("ADODB.") Recordset ")
Rs. Open "Select Statusname, Statusid from Employeestatus", _
"Dsn=employees;uid=sa;pwd=;"
s = "<select name=" "Employmentstatus" > "& vbCrLf
Set fldname = Rs. Fields ("Statusname") ' ADO field bindings
Do Until Rs. Eof
s = S & "<option>" & Fldname & "</option>" & VbCrLf
Rs. MoveNext
Loop
s = S & "</select>" & VbCrLf
Rs. Close
Set rs = Nothing ' free RS
Fetchemploymentstatuslist = S ' returns data in string form
End Function

In the correct case, you can cache the ADO recordset itself in the application or session range, but you must meet the following two conditions:. ADO must be marked as a free threading model (free-threaded). A connectionless recordset must be used

If the above two conditions are not met, you must not cache the recordset. In the following two tips for "inflexible components" and "Do not cache connection", we will discuss the dangers of saving COM objects in application and session.

When you store the data in a application or session, the data is saved until your program changes it, or the session expires, or the Web service restarts. What if the data needs to is updated? Manually refresh the application, you can invoke an ASP page that only the administrator can access to refresh the data, or periodically update the data periodically with a function. The following example saves a timestamp in the cached data and then automatically refreshes the data after a period of time.

<%
Const update_interval = 300 ' refresh interval, unit is seconds

' Return to Employee status list
Function getemploymentstatuslist
Updateemploymentstatus
Getemploymentstatuslist = Application ("Employmentstatuslist")
End Function

' Periodically update the data in the cache
Sub updateemploymentstatuslist
Dim D, Strlastupdate
Strlastupdate = Application ("Lastupdate")
If (strlastupdate = "") Or _
(Update_interval < DateDiff ("s", Strlastupdate, now) Then

' Note:two or more calls might get in. This is okay and
would simply
' result in a few unnecessary fetches (there is a workaround
For this)

' Fetchemploymentstatuslist function (not shown)
' Fetches data from DB, returns an Array
D = fetchemploymentstatuslist ()

' Update Application object with Application.Lock () to maintain data consistency
Application.Lock
Application ("employmentstatuslist") = Events
Application ("lastupdate") = CStr (now)
Application.UnLock
End If
End Sub

It's not a good idea to cache large arrays in session or application. Before any element in the array is accessed, the script interpreter needs to generate a temporary copy of the entire array. For example, if you cache an array of 100,000 string elements to match the ZIP code to the local weather by one by one, before accessing any of the strings in the array, the ASP interpreter must first replicate all 100,000 weather data into a temporary array. In this case, it is more appropriate to develop a component to store weather data or to use a dictionary (dictioary) object. However, also do not be wise and foolish, the array object's lookup rate is faster. Index a dictionary peso to guide an array slowly. You can choose the right data structure for your situation.

Tip 3: Cache data and HTML pages on your hard disk

Sometimes, there may be too much data cached in memory. "Too much" is a vague argument, depending on the size of the Web server's memory, the number of cached items, and how often these cached items are accessed. In any case, if too much data is cached in memory, consider caching the data with text or XML files on the Web server's hard disk. Can be cached to the hard disk and into the memory of the combination, for your site, find the most optimized strategy.

Note that when we measure the performance of a single ASP page, reading data from the hard disk may be slower than reading from the database. However, caching can reduce the load on the database and the network. In the case of high load, this will greatly increase overall throughput. When the cached data is a very complex query, such as a multiple-table connection or a complex query process or a very large recordset, the effect of caching is obvious.

ASP and COM provide a number of tools to build a disk-based caching scheme. The Save and open methods of the ADO Recordset object can be saved and mounted to disk. There are also a few components to access the file:. Scripting.FileSystemObject allows you to create, read, and write files. MSXML, Microsoft's XML interpreter bundled with IE, supports saving and loading XML documents. The LookupTable object is a great choice for loading a simple list from disk.

Finally, it is better to cache the data performance on the hard disk than the cached data itself. The generated HTML can be saved on your hard disk with an. htm or. asp file, and the hyperlinks can point directly to those files. You can also generate and process HTML files using a number of business tools, such as Xbuilder and SQL Server Internet Publishing features. Alternatively, you can include HTML fragments in an ASP file with #include, or you can use FileSystemObject to read HTML files.

  Tip 4: Avoid caching COM objects in application or session objects

While caching data in a application or Session object is a good note, caching a COM object can have serious consequences. Caching common COM objects in application or session objects is tempting, but unfortunately, many COM objects, including those written in VB 6.0 or earlier, are cached to
Application or session objects can cause serious performance bottlenecks.

In particular, all non-agile components will have performance bottlenecks when they are cached in session or application. The agile component refers to the aggregation of free-threaded marshaler (FTM) and the threading model is both
(Threadingmodel=both), or the threading model is neutral (netural new appears in Windows 2000
and COM +) components. The following components are non-agile:


Free threading model components (unless they aggregate the FTM)
Apartment Threading Model components
Single-threaded components

Configured components (mts/com+ libraries and service Packs/applications) are non-agile unless they are neutral threading models. Apartment threading Model components and other non-agile components are best to work within the page range (i.e., they are created and destroyed in a single ASP page).

In IIS 4.0, the threading model is a both component that is considered agile, but in IIS 5.0 they no longer meet the conditions of agile. The component threading model must be both and aggregated FTM to be considered agile. If you attempt to store a non-agile component created with Server.CreateObject to a
Application object, IIS 5.0 throws an error.

An ADO Recordset object can be stored securely when the ADO component is marked as a free threading model. You can use Makfre15.bat, typically in the \\program Files\common\system\ado folder, to mark the ADO component as a free threading model. One thing to note: ADO cannot be marked as a free threading model when you use Access as a background database. The dictionary (Dictionary) component is also an Agile object.

  Tip 5: Do not cache database connections

Caching ADO Connection objects is a bad strategy. If a connection object is stored in the
Application object and is used by all pages, all pages will struggle to use this connection. If
The connection object is stored in the session object, creating a database connection for each user, which cuts down the connection pool and increases the pressure on the Web server and database server. You can use an ASP page that uses ADO to create and release ADO objects in place of a cached database connection, which is very effective because the database connection pool is built into IIS.

Since a connected Recordset holds a reference to a database connection, you should not save a connected recordset in a application or Session object. However, you can safely cache a connectionless recordset because it does not contain a reference to a data connection. To hang up a recordset, you can take the following two steps:

Set rs = Server.CreateObject ("ADODB.") RecordSet ")
Rs. CursorLocation = adUseClient ' First step

Rs. Open strquery, Strprov

' Hang the recordset with the data provider and the data source
Rs. ActiveConnection = Nothing ' second step

  Tip 6: Use the Session object correctly

We've mentioned the benefits of caching data in application and session, and we'll say some of the following
The disadvantage of the session object. Using a session on a busy site has some disadvantages. Busy refers to the site processing hundreds of page requests per second or simultaneously connecting thousands of concurrent users. This technique is important for those sites that have to scale horizontally-that is, they use multiple servers for load balancing or fault tolerance. For small sites, such as the company intranet, session relative to his consumption of resources, it is worth a use.

The ASP automatically creates a session object for each support that accesses the Web server. Each session consumes about 10K of resources and makes all requests slower. This session persists throughout the timeout period, which is typically 20 minutes. The biggest problem for session is not performance but scalability. The session is not a cross Web server, and once it is created on a server, its data is stored there.
This means that if you want to use session in multiple Web server environments, you must design a policy that allows the user to always access the Web server on which the session object resides, and to glue a user to a Web server. If the Web server crashes because the session is not permanently saved on the disk hungry, so all "sticky"
The session state of the user on it will be lost. Policies that implement the sticky session include hardware and software scenarios, such as the network Load balancing in Windows Advanced Server and the local Director of Cisco. Of course, these schemes are not perfect, and they have to lose some scalability. Application objects are also not cross servers, and if you want to share and update application data between multiple servers, you must use a background database. However, read-only application data is useful in a multiple-server environment.

Most mission-first (mission-critical) sites want to publish on at least two Web servers-if there is no more important reason to extend uptime. Therefore, in the design phase, you need to implement "sticky session" or simply avoid session and other state management techniques that save user state on a separate Web server.

If you do not use session, turn them off; You can turn off the session functionality of your application through Internet Service Manager (see ISM documentation). If you decide to use session, there are some ways to minimize their impact on performance. You can move content that does not need a session, such as a Help window, into an ASP application that closes the session. If a single page does not require a session, you can place the following statement at the top of the page to prevent session functionality:

<% @EnableSessionState =false%>

Another reason for using this statement is that the session creates an interesting problem in the frame. ASP guarantees that at any time a session has only one request, which causes if the browser requests multiple pages at the same time, only one ASP request will be able to access sessions at the same moment; this avoids the multithreading problem that occurs when you access an object; but unfortunately, multiple pages in one frame can only be generated sequentially , one after the other, not the art of war. Users may wait longer for multiple frames. So if a page in a frame doesn't use session, place the <% @EnableSessionState =false%> statement at the top of the page.

As an alternative to using the session object, there are many other ways to manage conversational state. For small-scale states (less than 4KB), it is recommended that you use cookies,querystring variables and hidden form variables. For a lot of data, such as shopping information, a background database may be a good choice.

  Tip 7: Encapsulate code in a COM object

If you have a lot of VBScript or JScript code, you can improve performance by encapsulating code in a COM object.
Compiled code usually runs faster than an interpreted code. COM objects can access other COM objects through "early binding", which is more efficient than "late binding" used by the script.

The following are the advantages of encapsulating code into a COM object (not just performance):

COM objects can be a good way to separate business logic from performance logic
COM objects to make code reusable
Code written with Vb,c or VJ is easier to debug than ASP code

COM objects are also deficient, including long development cycles and the need for different programming experiences. It is particularly important to note that encapsulating a small number of ASP code can backfire on performance; In this case, the cost of creating and invoking COM objects exceeds the benefit of compiling code performance. How to combine ASP code and COM component code to produce optimal performance is often a headache. Note that Windows 2000/iis 5.0 has significantly improved scripting and ADO performance compared to Windows NT 4.0/iis 4.0.

  Tip 8: Late access to resources, early release

In general, late acquisition and early release of resources are best. This applies not only to COM objects, but also to file handles and other resources. The ADO connection and Recordset are the main objects of this optimization strategy. When you are finished using a Recordset object, you should immediately release it instead of waiting for the page to end. Setting the VBScript variable to nothing is the best way to do it. Also, release the associated Command and connection objects (don't forget to call the close () method before you set the connection object to nothing).

  Tip 9: out-of-process execution with performance in return for reliability

Both ASP and mts/com+ have options for you to use reliability in exchange for performance. When you build and publish your application, you should understand the insider of the deal.

ASP options

There are three ways to run ASP applications. In IIS 5.0, the term "detach level" is introduced to describe these options isolation. The three separation levels are: low (lower), Medium (Medium) and high.

This level of low separation level is supported by all versions of IIS and is the fastest speed. It runs ASP in inetinfo.exe--, the main IIS process. If the ASP application crashes, IIS will also crash.

(In IIS 4.0, a network administrator must use tools such as Inetmon to monitor IIS, and once IIS stops, run the batch file.) IIS 5.0 introduces a "reliable reboot (reliable restart)", which automatically restarts the failed server.

The new level in which the detach level is introduced from IIS 5.0, which is run out-of-process, where the ASP runs outside the IIS process. In the split level, all ASP applications share a process space. Applying multiple processes outside the same space to run, reducing the process of the trees. The split level in is the default level for IIS 5.0.

High-Detach IIS 4.0 and IIS 5.0 are supported. The high separation level is also outside the process. If the ASP crashes, the Web server does not crash. ASP applications are automatically restarted when the next ASP request arrives. Each ASP application configured as a high level of separation has its own process space, which protects each ASP application. Its disadvantage is that each ASP application requires a separate process; This adds a lot of resource consumption.

Which option is the best. In IIS 4.0, the process shipping line will dramatically degrade performance, and in IIS 5.0, many improvements minimize the cost of out-of-process ASP applications. In fact, in many tests, the ASP out-of-process application in IIS 5.0 runs faster than in the process in II4 4.0. However, in any platform, or in the process (low separation level) of the operation can bring the best performance. However, low separation levels do not provide any benefit in the case of relatively low click-through or low maximum throughput, so you won't need to use a low level of separation unless each Web server has to cope with hundreds of page requests. Typically, you need to test under multiple configurations to determine which configuration to use.

Note: When running ASP applications outside the process (medium or low level), ASP applications run in MTS on NT 4 or in COM + in Windows 2000, i.e., in NT4, ASP applications run in Mtx.exe;
In Windows 2000, ASP applications run in DllHost.exe. You can see these processes running in Task Manager.

COM options

COM components also have three configuration options, but do not fully correspond to ASP's options. COM components can be "unconfigured", either as a library application (library application) or as a service application (Server application). "No configuration" means that the component is not registered in COM + and that the component will run in the caller process space, that is, in-process. Library applications are also in-process, but can benefit from COM + services, such as security, transaction, and context support. Service applications are configured to run in their own process space.

"No Configuration" is a bit more advantageous than library applications, and library applications are superior in performance to service applications. This is because the library application and the ASP are within the same process, and the service application is running in its own process space. Inter-process calls are more expensive than in-process calls. Similarly, passing data, such as a recordset, between processes requires copying all of the data between two processes.

Defects! When using COM Service applications, to transfer data between ASP and COM, it is necessary to ensure that the object implements the "by Value (Marshall-by-valu)", or MBV. The object that implements the MBV copies itself from one process to another. This is better than the following method: The object remains in the creator process, and the other processes repeatedly invoke the creation process to use the object. The connectionless ADO Recordset is MBV, and there is no connection recordset.

The Scripting.dictonary object does not implement MBV and cannot be passed between processes. Finally, a hint to VB programmer: MBV not by using ByVal to pass parameters. MBV is implemented by the original component author.

What do you do?
Recommended configurations for performance in return for reliability:

On IIS 4.0, use the low separation level of ASP and use MTS service packs.
In IIS 5.0SHANG, use COM + 's library application with the medium separation level of ASP.

  Tip 10: Use option Explicit

Use option Explicit in the. asp file. The directive is placed at the top of the. asp file, forcing the developer to define it before using any variables. Many programmers think this helps debug the program because it eliminates the possibility of typing errors (such as knocking myxmlstring= into myxlmstring=)

Another point may be more important: defined variables are faster than undefined variables. The ASP uses the name to refer to undefined variables each time, and on the other hand, each defined variable has an ordinal number, which is used by ASP to refer to the defined variable. Since Option Explicit enforces variable definitions, it ensures that all variables are defined and accessed faster.

Tip 11: Use local variables in child procedures and functions

Local variables are those that are defined in child procedures and functions. In functions and subroutines, it is quicker to access local variables than to access global variables. Using local variables also makes the code cleaner, so use local variables as much as possible.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.