gpt4 book ai didi

arrays - 循环范围与循环数组之间的性能差异

转载 作者:行者123 更新时间:2023-12-04 21:16:11 25 4
gpt4 key购买 nike

循环遍历范围与将相同范围分配给数组并循环数组时,性能(速度)会有所不同吗?

最佳答案

遍历数组比查看范围要快得多。

请参阅下面的测试:

Option Explicit

Const strRANGE_ADDRESS As String = "A1:A100000"

Sub LoopRangeAddOne()

Dim r As Range
Dim lStart As Double
Dim lEnd As Double

lStart = Timer

For Each r In Range(strRANGE_ADDRESS)
r.Value = r.Value + 1
Next r

lEnd = Timer

Debug.Print "Duration = " & (lEnd - lStart) & " seconds"

End Sub

Sub LoopArrayAddOne()

Dim varArray As Variant
Dim var As Variant
Dim lStart As Double
Dim lEnd As Double

lStart = Timer

varArray = Range(strRANGE_ADDRESS).Value
For Each var In varArray
var = var + 1
Next var
Range(strRANGE_ADDRESS).Value = varArray

lEnd = Timer

Debug.Print "Duration = " & (lEnd - lStart) & " seconds"

End Sub

结果:

LoopRangeAddOne 持续时间 = 2.2734375 秒

LoopArrayAddOne 持续时间 = 0.08203125 秒

这使得通过数组循环比通过循环快 96.39%。

希望这可以帮助 :)

关于arrays - 循环范围与循环数组之间的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33302962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com