|
|
Technical Article Library
ActiveX Controls For VB ·
Dispelling the For...Next myth (finally, an undebatable
conclusion)
When you write a For loop, do you include the variable name
after the Next? Of course, you say. "I heard it was faster". Some of
you are also saying "I heard that leaving the variable name off was
faster". Maybe some of you will point to some benchmark showing one
or the other is faster. Well, here is the final, definitive answer.
Period. You may be surprised...
Here is the test code. It has two loops. One with the variable name
after Next, and one without. In between, we reset a variable to
zero.
Public
Sub Main()
Dim i
As Long
Dim x As
Long
' Without
For i = 1
To 100
x = x + 1
Next
x = 0
' With
For i = 1
To 100
x = x + 1
Next i
End Sub
When compiled, this code generates the following assembly code
listing:
;For i = 1 To 100
004019F9 mov dword ptr
[unnamed_var1],64h
00401A00 mov
dword ptr [unnamed_var1],1
00401A07 mov
dword ptr [i],1
00401A0E jmp
Module1::Main+35h (401A19h)
;x = x + 1
00401A10 mov
eax,dword ptr [i]
00401A13 add
eax,dword ptr [unnamed_var1]
00401A16 mov
dword ptr [i],eax
00401A19 mov
eax,dword ptr [i]
00401A1C cmp
eax,dword ptr [unnamed_var1]
00401A1F jg
Module1::Main+46h (401A2Ah)
00401A21 mov
eax,dword ptr [x]
00401A24 inc
eax
00401A25 mov
dword ptr [x],eax
;Next
00401A28 jmp
Module1::Main+2Ch (401A10h)
;x = 0
00401A2A and
dword ptr [x],0
;For i = 1 To 100
00401A2E mov
dword ptr [unnamed_var1],64h
00401A35 mov
dword ptr [unnamed_var1],1
00401A3C mov
dword ptr [i],1
00401A43 jmp
Module1::Main+6Ah (401A4Eh)
;x = x + 1
00401A45 mov
eax,dword ptr [i]
00401A48 add
eax,dword ptr [unnamed_var1]
00401A4B mov
dword ptr [i],eax
00401A4E mov
eax,dword ptr [i]
00401A51 cmp
eax,dword ptr [unnamed_var1]
00401A54 jg
Module1::Main+7Bh (401A5Fh)
00401A56 mov
eax,dword ptr [x]
00401A59 inc
eax
00401A5A mov
dword ptr [x],eax
;Next i
00401A5D jmp
Module1::Main+61h (401A45h)
Looking at the assembly code produced by the VB6 compiler, it is
completely obvious that there is absolutely no difference between the
two loops. None. Not even a little. Any benchmark showing one to be
faster than the other is flawed.
So what does this mean? It doesn't matter if you type the loop variable
after the Next or not. Seriously, everybody can stop arguing about it
now. It is settled.
Coming up next, the truth about method calls in a For...Next
declaration...
|
RSS
Please subscribe to our RSS feed to be informed whenever we post a
new article here.
Our feed is located at:
http://www.teebo.com/tssrss.xml
If you do not currently have an RSS reader, we recommend:
RSS Bandit
|