On Friday, 10 February 2017 at 12:39:50 UTC, Bastiaan Veelo wrote:
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!

The foreach loop behaves differently.
It does not modify d.

If you want it to modify the array you have to use a ref elem.
If you do you will see that foreach is a little slower.

Reply via email to