D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6898 - Some built-in optimizations for tuples
Summary: Some built-in optimizations for tuples
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2011-11-06 01:23 UTC by bearophile_hugs
Modified: 2021-01-24 06:30 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2011-11-06 01:23:41 UTC
One of the disadvantages of using library-defined types is the relative lack of higher-level optimizations done on them. Tuples are a fundamental data type, about as much fundamental as arrays, and they are meant to be used everywhere in programs; and I don't think it's wise to rely too much on D back-ends to optimize tuple operations a lot. So I think it's a job for the D front-end.

As example of such basic tuple optimizations to be implemented in a good D front-end, I expect the fib2 program below to produce an assembly code similar to the assembly of fib1 (in DMD 2.057head this optimization is not done. Similar basic optimization is needed to use tuples freely in D code, otherwise D tuples are usable only in non performance critical code, and their usefulness is reduced significantly):


import std.stdio, std.bigint, std.algorithm, std.range, std.typecons;

T fib1(T)(T n) {
    auto a = cast(T)1;
    auto b = a;
    foreach (i; cast(T)1 .. n) {
        auto aux = b;
        b = a + b;
        a = aux;
    }
    return a;
}

T fib2(T)(T n) {
    auto ab = tuple(cast(T)1, cast(T)1);
    foreach (i; cast(T)1 .. n)
        ab = tuple(ab[1], ab[0] + ab[1]);
    return ab[0];
}

void main() {
    foreach (i; BigInt(1) .. BigInt(20))
        write(fib1(i), " ");
    writeln();

    foreach (i; BigInt(1) .. BigInt(20))
        write(fib2(i), " ");
}
Comment 1 mhh 2021-01-24 06:30:09 UTC
Vague + https://gist.github.com/maxhaton/7fc69be09e4d4fcd1fa5c3df6e371f49 (ldc seems to do a good job)