如果您要执行固定数量的迭代的代码段,请始终使用For ... Next循环而不是Do ... Loop,因为这样做的速度明显更快。 每次循环执行Do ... Loop都会重复指定的次数,还要求您也实现或减少某种循环计数器,而For ... Next循环则可以为您工作。 两个循环将提供相同的结果,但是For ... Next循环的速度明显更快。 值得一提的是,您不能总是用For ... Next替换Do ... Loop,如果循环迭代的数目是固定的,并且不是基于在某些逻辑条件下。
我创建了一些简单的基准测试,涉及3个使用timeGetTime()API函数比较这两个循环的效率的试验。 还计算了两个过程的比较比率,使您可以更好地了解这两个比较。 我将在下面发布基准测试的代码。 如有任何疑问,请随时提问。
'Declaration needed for API Call
Public Declare Function timeGetTime Lib "winmm.dll" () As Long
Dim lngCounter As Long
Dim lngStart_1 As Long
Dim lngStart_2 As Long
Dim lngStop_1 As Long
Dim lngStop_2 As Long
Dim varTestVariable As Variant
Const conNUM_OF_ITERATIONS As Long = 10000000
'******************************* 1st up, For...Next *******************************
lngStart_1 = timeGetTime()
For lngCounter = 1 To conNUM_OF_ITERATIONS
'do some processing here
varTestVariable = (lngCounter / 0.25) * 1.5
Next
lngStop_1 = timeGetTime()
Debug.Print "For...Next took (" & FormatNumber((lngStop_1 - lngStart_1), 0) & _
") milliseconds to execute the expression"
'**********************************************************************************
'******************************* 2nd up, Do...Loop ********************************
lngCounter = 1
lngStart_2 = timeGetTime()
Do Until lngCounter > conNUM_OF_ITERATIONS
'same processing here as for the For...Next Loop
varTestVariable = (lngCounter / 0.25) * 1.5
lngCounter = lngCounter + 1
Loop
lngStop_2 = timeGetTime()
Debug.Print "Do...Loop took (" & FormatNumber((lngStop_2 - lngStart_2), 0) & _
") milliseconds to execute the expression"
'**********************************************************************************
Debug.Print "The For...Next Loop executed the same code in [" & _
Format((lngStop_1 - lngStart_1) / (lngStop_2 - lngStart_2), "Percent") & _
"] of the time it took Do...Loop!"
输出:
For...Next took (766) milliseconds to execute the expression
Do...Loop took (1,515) milliseconds to execute the expression
The For...Next Loop executed the same code in [50.56%] of the time it took Do...Loop!
For...Next took (781) milliseconds to execute the expression
Do...Loop took (1,516) milliseconds to execute the expression
The For...Next Loop executed the same code in [51.52%] of the time it took Do...Loop!
For...Next took (781) milliseconds to execute the expression
Do...Loop took (1,532) milliseconds to execute the expression
The For...Next Loop executed the same code in [50.98%] of the time it took Do...Loop!
注意: Access 2002开发人员手册指出,For ... Next循环运行Do ... Loop进行比较代码的时间大约为45%。
根据上面列出的代码段,我的个人测试显示,根据“ 3次试用”的平均值,这个数字约为51.02%。
From: https://bytes.com/topic/access/insights/797078-next-vs-do-loop-winner