asp程序代碼優化

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毫秒

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章