Site
News
Files Visual Basic
Strings
Math
General
Properties
Memory
Methods Search
Testing Inline ASM-VB
Strings
Math
General
Memory Search
Using inline ASM
Submit!
News
Files Visual Basic
Strings
Math
General
Properties
Memory
Methods Search
Testing Inline ASM-VB
Strings
Math
General
Memory Search
Using inline ASM
Submit!
For…Each vs. For...NextUsing For...Next in arrays is a lot faster than For...Each.
I'm not sure why this is caused, but probably also because you've got to use a variant as loop index for the "For...Each".
And any serious programmer doesn't use a variant in his/her applications.
I've used Lbound() and Ubound() in the For...Next loop, cause we do not have to worry about those two values, like in For...Each.
No 500.000 iterations this time. I've done 1 iteration, the array was large enough to be precise enough. The test has been done 5 times though.
Used Code:
User contributed notes:
Code: |
For...Each % faster than For...Next | For...Each (sec) | For...Next (sec) |
69,8% | 0.070230 | 0.041363 |
39% | 0.062214 | 0.044772 |
51,5% | 0.062389 | 0.041175 |
30,9% | 0.062814 | 0.047993 |
51,3% | 0.061905 | 0.040924 |
User contributed notes:
Author: fish () | Date: 17:09 04/09/2004 |
for collections, always use for each, it's many times faster | |
Author: SuperDre () | Date: 10:06 23/06/2006 |
I agree with fish(), For Each isn't meant for using with simple arrays (it also only works with arrays of variants). And you made one other mistake, you only do a loop with nothing in it.. Try doing the same test but then assign something to the item.. I think you will get a completely different result then.. Because with every assignment, For..Next has to lookup the item every cycle, whereas For Each already has the Item.. |