Why is for() less efficient than foreach?

Bastiaan Veelo via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 10 04:39:50 PST 2017


Benchmarking for() against foreach():

/////////
enum size_t maxarray = 500_000;

double[maxarray] a, b, c, d;

void main()
{
     import std.stdio;
     import std.datetime;

     import std.random;
     for (int n = 0; n < maxarray; n++)
     {
         a[n] = uniform01;
         b[n] = uniform01;
         c[n] = uniform01 + 0.1;
     }

     void overhead() {}

     void foreach_loop()
     {
         foreach(n, elem; d[])
             elem = a[n] * b[n] / c[n];
     }

     void for_loop()
     {
         for (int n = 0; n < maxarray; n++)
             d[n] = a[n] * b[n] / c[n];
     }

     auto r = benchmark!(overhead,
                         foreach_loop,
                         for_loop)(10_000);

     import std.conv : to;
     foreach (i, d; r)
         writeln("Function ", i, " took: ", d.to!Duration);
}
/////////


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!


More information about the Digitalmars-d-learn mailing list