Why is for() less efficient than foreach?

evilrat via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 10 05:13:24 PST 2017


On Friday, 10 February 2017 at 12:39:50 UTC, Bastiaan Veelo wrote:
> Depending on the machine this is run on, for() performs a 
> factor 3-8 slower than foreach(). Can someone explain this to 
> me? Or, taking for() as the norm, how can foreach() be so 
> blazingly fast?
> Thanks!

On my machine (AMD FX-8350) actually almost no difference

DMD 2.073
dmd -run loops.d -release
Function 0 took: 16 ╬╝s and 5 hnsecs
Function 1 took: 57 secs, 424 ms, and 555 ╬╝s
Function 2 took: 53 secs, 494 ms, 709 ╬╝s, and 8 hnsecs


LDC 1.1.0-beta6
ldc2 -run loops.d  -release -o3
Using Visual C++: C:\Program Files (x86)\Microsoft Visual Studio 
14.0\VC
Function 0 took: 25 ╬╝s and 5 hnsecs
Function 1 took: 53 secs, 253 ╬╝s, and 8 hnsecs
Function 2 took: 56 secs, 76 ms, 656 ╬╝s, and 4 hnsecs


More information about the Digitalmars-d-learn mailing list