asp程序代码优化

来源:互联网 发布:复方川羚定喘胶囊 淘宝 编辑:程序博客网 时间:2024/06/07 03:42

1、  声明VBscript变量
在ASP中,对vbscript提供了强劲的支持,能够无缝集成vbscript的函数、方法,这样给扩展ASP的现有功能提供了很大便利。由于ASP中已经模糊了变量类型的概念,所以,在进行ASP与vbscript交互的过程中,很多程序员也惯于不声明vbscript的变量,这样加重了服务器的解析负担,进而影响服务器的响应请求速度。
鉴于此,我们可以象在VB中强制用户进行变量声明一样在vbscript中强制用户进行变量声明。实现方法是在ASP程序行首放置<% optionexplicit%>。
2、  对URL地址进行编码
在我们使用asp动态生成一个带参数URL地址并进行跳转时,在IE中解析很正常,但在NetScrape浏览时却有错误如下:
HTTP Error 400
400 Bad Request
Due to malformed syntax, the request could not be understood by the server.
The client should not repeat the request without modifications.
解决方法是对生成的URL参数使用ASP内置server对象的URLencode方法进行URL编码,例子如下:
<%
URL="xur.asp"
var1="username=" & server.URLencode("xur")
var2="&company=" & server.URLencode("xurstudio")
var3="&phone=" & server.URLencode("021-53854336-186")
response.redirect URL & "?" & var1 & var2 & var3
%>
3、  清空对象
当使用完对象后,首先使用Close方法来释放对象所占用的系统资源;然后设置对象值为“nothing”释放对象占用内存。下面的代码使用数据库内容建立一个下拉列表。代码示例如下:
<% myDSN="DSN=xur;uid=xur;pwd=xur"
mySQL="select * from authors where AU_ID<100"
set conntemp=server.createobject("adodb.connection")
conntemp.open myDSN
set rstemp=conntemp.execute(mySQL)
if rstemp.eof then
response.write "数据库为空"
response.write mySQL
conntemp.close
set conntemp=nothing
response.end
 end if%>
<%do until rstemp.eof %>
<%
rstemp.movenext
loop
rstemp.close
set rstemp=nothing
conntemp.close
set conntemp=nothing
%>
4、使用字符串建立SQL查询
使用字符串来建立查询并不能加快服务器的解析速度,相反,它还会增加服务器的解析时间。但在这里仍然推荐使用字符串代替简单的查询语句来进行查询。这样做的好处是,可以迅速发现程序问题所在,从而便利高效地生成程序。示例如下:
<%mySQL= ""select * "
mySQL= mySQL & "from publishers"
mySQL= mySQL & "where state='NY'"
response.write mySQL
set rstemp=conntemp.execute(mySQL)
rstemp.close
set rstemp=nothing
%>
5、  使用case进行条件选择
在进行条件选择的时候,尽量使用case语句,避免使用if语句。使用case语句,可以使程序流程化,执行起来也比if语句来的快。示例如下:
<%
  FOR i = 1 TO 1000
   n = i
   Response.Write AddSuffix(n) & "<br>"
  NEXT
  %>
  <%
  Function AddSuffix(num)
numpart = RIGHT(num,1)
SELECT CASE numpart
CASE "1"
IF InStr(num,"11") THEN
num = num & "th"
ELSE
num = num & "st"
END IF
CASE "2"
IF InStr(num,"12") THEN
num = num & "th"
ELSE
num = num & "nd"
END IF
CASE "3"
IF InStr(num,"13") THEN
num = num & "th"
ELSE
num = num & "rd"
END IF
CASE "4"
num = num & "th"
CASE ELSE
num = num & "th"
END SELECT
AddSuffix = num
  END FUNCTION
%>
6.在ASP中, 使用GetRows与不使用GetRows而直接用Record来循环调用, 两者其实有所差别, 下面是测试:  调用记录数: 484  使用GetRows, 然后用数组来显示, 发现单花在GetRows的运算上花了约620毫秒. 总共花了711毫秒  直接用RecordSet来循环调用, 总共花了931毫秒  所以建议大家使用GetRows, 特别是要显示很多的返回记录时, 但是它会占用一部分临时内存.  在直接使用RecordSet时, 大部分时间是花费在游标的移动上, 大概占了90%以上  
7.表:DataTable  记录:5435  时间单位:毫秒
select * from DataTable order by id desc    时间:796毫秒
select * from DataTable where id>0 order by id desc    时间:406毫秒
select * from DataTable    时间:1920毫秒
select top 5435 * from DataTable order by id desc      时间:1280毫秒
select top 5435 * from DataTable     时间:1470毫秒
select id from DataTable order by id desc       时间:30毫秒

原创粉丝点击