萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 數組查找函數 InArray:雙重實現與性能對比

ASP 判斷值是否存在於數組:InArray 函數兩種實現與優化

ASP 原生無 InArray 函數,開發者常需自行實現。本文提供兩種經典寫法(For Each 與 For 索引),分析性能差異,並給出現代化擴展版本。

版本一:For Each 枚舉器模式

Function InArray_ForEach(sValue, aArray)
    Dim x
    InArray_ForEach = False
    For Each x In aArray
        If x = sValue Then
            InArray_ForEach = True
            Exit For
        End If
    Next
End Function

特點:代碼簡潔、語義清晰、自動處理任意下界數組。

版本二:For 索引訪問模式

Function InArray_Index(sValue, aArray)
    Dim i
    InArray_Index = False
    For i = 0 To UBound(aArray)
        If aArray(i) = sValue Then
            InArray_Index = True
            Exit For
        End If
    Next
End Function

特點:顯式控制索引、可擴展獲取位置、對非標準下界數組需調整。

性能微基準測試

<%
Dim testArr, i, start, t1, t2
ReDim testArr(10000)
For i = 0 To 10000 : testArr(i) = CStr(i) : Next

' 測試 For Each
start = Timer()
For i = 1 To 1000 : InArray_ForEach "9999", testArr : Next
t1 = Timer() - start

' 測試 For Index
start = Timer()
For i = 1 To 1000 : InArray_Index "9999", testArr : Next
t2 = Timer() - start

Response.Write "For Each: " & FormatNumber(t1*1000,2) & "ms
" Response.Write "For Index: " & FormatNumber(t2*1000,2) & "ms
" %>

典型結果:For Index 快 10-20%(避免枚舉器創建開銷),但在 10 萬級以下數組差異可忽略。

增強版:返回索引、支持大小寫、泛型比較器

Function InArrayEx(sValue, aArray, Optional caseSensitive, Optional comparer)
    Dim i, cmpResult
    If IsMissing(caseSensitive) Then caseSensitive = False
    If IsMissing(comparer) Then Set comparer = Nothing
    
    For i = LBound(aArray) To UBound(aArray)
        If IsObject(comparer) Then
            cmpResult = comparer.Compare(aArray(i), sValue)
        ElseIf caseSensitive Then
            cmpResult = IIf(StrComp(aArray(i), sValue, vbBinaryCompare) = 0, 0, 1)
        Else
            cmpResult = IIf(StrComp(aArray(i), sValue, vbTextCompare) = 0, 0, 1)
        End If
        
        If cmpResult = 0 Then
            InArrayEx = i  ' 返回索引(>=0 表示找到)
            Exit Function
        End If
    Next
    InArrayEx = -1  ' 未找到
End Function

' 用法
Dim idx
idx = InArrayEx("test", myArr, False)  ' 不區分大小寫
If idx >= 0 Then Response.Write "找到於索引 " & idx

最佳實踐建議

  • 高頻查找(>1000 次/請求)時,將數組轉為 Scripting.Dictionary,O(1) 查找:dict.Exists(key)。
  • 數組靜態不變時,排序後用二分查找 O(log n)。
  • 避免在大循環中重複調用 InArray,預先構建查找表。

Dictionary 替代方案

Function ArrayToDict(aArray)
    Dim dict, i : Set dict = CreateObject("Scripting.Dictionary")
    For i = LBound(aArray) To UBound(aArray)
        dict(aArray(i)) = i  ' 值存索引
    Next
    Set ArrayToDict = dict
End Function

' 使用
Dim dict : Set dict = ArrayToDict(myArr)
If dict.Exists("target") Then Response.Write "索引: " & dict("target")

選擇合適的查找策略,能讓 ASP 數據處理效率提升數量級。

copyright © 萬盛學電腦網 all rights reserved