On Tuesday, 2 October 2012 at 20:48:31 UTC, ixid wrote:
Without optimization the range and algorithm method takes about 10 times as long as the simple code below it, with no array bounds checking and optimization it takes six times as long. Why is the difference so huge? I'd expect a moderate overhead but that's a big difference.

module main;
import std.stdio, std.algorithm, std.range, std.datetime;

enum MAX = 10_000_000UL;

void main() {
        StopWatch sw;
        sw.start;

        auto sum1 = MAX.iota.map!(x => x * x).reduce!"a + b";

        sw.peek.msecs.writeln("msecs");
        sum1.writeln;
        sw.start;

        ulong sum2 = 0;
        foreach(i;0..MAX)
                sum2 += i * i;

        sw.peek.msecs.writeln("msecs");

        sum2.writeln;
}

I realised I was making the functional version more complicated than necessary. This version is faster but still four times slower than the simple version:

MAX.iota.reduce!"a + b * b".writeln;

Reply via email to