日期:2010-04-22  浏览次数:21068 次

  技巧1:将常用数据在Web服务器端缓存起来 

  大部分的ASP页面都要从后台数据库中提取数据,然后将数据用HTML方式表现出来。 
不管你的数据库多么快,从内存中提取数据总比从后台数据库中提取快;从本地硬盘中读取数据通常也比从数据库中快。因此,你可以通过在Web服务器端缓存数据来提高性能。 

  缓存是个典型的以空间换取时间的交易。如果你正确的缓存了数据,性能可能会突飞猛进。要想一个缓存能真正发挥效益,必须缓冲那些常用和计算复杂的数据。装满过期数据的缓冲区只能浪费内存。 

  不经常变化的数据也是缓存的一个良好候选者,因为你可以不用关心同数据库中的数据保持同步。下拉列表框、引用表、小段DHTML代码,XML字符串、菜单项和站点配置变量(包括数据源名字(DSN),IP地址和Web路径)都是很好的缓存候选者。注意,不仅仅可以缓存数据本身,还可以缓存数据的表现。如果一个ASP页面很少变化,并且缓存代价比较高(比如,产品列表),可以考虑用静态HTML页面。

  技巧2:用Application对象或Session对象缓存常用数据 

  ASP的Application和Session对象是一个极其方便的在内存中缓存数据的容器。你可以把数据放到Application或Session对象中,这些数据就会在整个HTTP调用中一直存在。每个用户有自己的Session对象中的数据,而Application对象中的数据可以在所有用户中共享。 

  应该在什么时候将数据装入Application或Session中呢?通常,数据在Application或Session启动的时候装入。要想在Application或Session启动的时候装入数据,需要分别在Global.asa的Application_OnStart()或Session_OnStart()中添加适当的代码;如果Global.asa中没有这两个函数,你可以手工添加。也可以在数据第一次使用的时候将其装入。要想这样,应该在ASP页面中写一些代码(或是写一个可重用的脚本函数)来检查数据是否存在并且如果数据不存在则将其装入内存。下面是一个经典的性能调整技术--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 be written for each chunk of data needed. 

In what format should the data be stored? Any variant type can be 
stored, since all script variables are variants. For instance, you 
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 an ADO recordset, you 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 using GetRows() to 
return an array of recordset data: 

' 获取记录集,返回数组 
Function FetchEmploymentStatusList 
 Dim rs 
 Set rs = CreateObject("ADODB.Recordset") 
 rs.Open "select StatusName, StatusID from EmployeeStatus", _ 
     "dsn=employees;uid=sa;pwd=;" 
 FetchEmploymentStatusList = rs.GetRows() ' 将记录集用数组返回 
 rs.Close 
 Set rs = Nothing 
End Function 

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

' 获取记录集,返回HTML Option列表 
Function FetchEmploymentStatusList 
 Dim rs, fldName, s 
 Set rs = CreateObject("ADODB.Recordset")