訪問(wèn)簡(jiǎn)單變量總是快于數(shù)組元素值

字號(hào):

讀寫(xiě)數(shù)組中的元素速度通常都慢于訪問(wèn)一個(gè)簡(jiǎn)單變量,因此,如果在一個(gè)循環(huán)中要重復(fù)使用同一數(shù)組元素值,就應(yīng)該分配數(shù)組元素值到臨時(shí)變量中并使用這個(gè)變量。下面舉一個(gè)例子,檢測(cè)整數(shù)數(shù)組中是否存在重復(fù)項(xiàng):
    Function AnyDuplicates(intArray() As Integer) As Boolean
    '如果數(shù)組包含重復(fù)項(xiàng),返回True
    Dim i As Long, j As Long,
    Dim lastItem As Long
    Dim value As Integer
    '只計(jì)算機(jī)UBound()一次
    lastItem = UBound(intArray)
    For i = LBound(intArray) To lastItem
    ' 保存intArray(i)到非數(shù)組變量中
    value = intArray(i)
    For j = i + 1 To lastItem
    If value = intArray(j) Then
    AnyDuplicates = True
    Exit Function
    End If
    Next
    Next
    '沒(méi)有發(fā)現(xiàn)重復(fù)項(xiàng)
    AnyDuplicates = False
    End Function
    上述程序有2層循環(huán),通過(guò)緩存intArray(i)的數(shù)值到一個(gè)普通的、非數(shù)組變量中,節(jié)省了CPU運(yùn)行時(shí)間。經(jīng)測(cè)試,這將提高80%的速度。