[Issue 16120] New: dmd does not inline simple range primitives

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sat Jun 4 09:27:21 PDT 2016


https://issues.dlang.org/show_bug.cgi?id=16120

          Issue ID: 16120
           Summary: dmd does not inline simple range primitives
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: greensunny12 at gmail.com

observation 1) dmd doesn't inline range primitives (it's 8x slower!)
observation 2) foreach with direct random access is lower in dmd (30%)

simple benchmark yields

```
> dmd -release -O foo.d && ./foo
0 881 ms, 351 μs, and 9 hnsecs
1 685 ms, 888 μs, and 4 hnsecs
2 685 ms, 654 μs, and 4 hnsecs
3 7 secs, 211 ms, 530 μs, and 3 hnsecs
```

for:

auto f_random_access(R)(R r)
{
    auto sum = 0;
    foreach (const i; 0 .. r.length)
    {
        sum += r[i];
    }
    return sum;
}

auto f_foreach(R)(R r)
{
    auto sum = 0;
    foreach (const el; r)
    {
        sum += el;
    }
    return sum;
}

auto f_foreach_ref(R)(R r)
{
    auto sum = 0;
    foreach (const ref el; r)
    {
        sum += el;
    }
    return sum;
}

auto f_for(R)(R r)
{
    import std.range;
    auto sum = 0;
    for (r.popFront(); !r.empty; r.popFront())
    {
        sum += r.front;
    }
    return sum;
}

void main() {
    import std.datetime: benchmark, Duration;
    import std.stdio: writeln;
    import std.array: array;
    import std.conv: to;
    import std.random: randomShuffle;
    import std.range:iota;
    auto arr = iota(100_000).array;
    arr.randomShuffle;

    auto i = 0;

    void f0(){ i += arr.f_random_access; }
    void f1(){ i += arr.f_foreach; }
    void f2(){ i += arr.f_foreach_ref; }
    void f3(){ i += arr.f_for; }
    auto rs = benchmark!(f0, f1, f2, f3)(10_000);
    foreach(j,r;rs)
        writeln(j, " ", r.to!Duration);

    // prevent any optimization
    writeln(i);
}

--


More information about the Digitalmars-d-bugs mailing list