Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize with switches some associative array usage idioms #17660

Open
dlangBugzillaToGithub opened this issue May 21, 2014 · 0 comments
Open

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2014-05-21T23:23:00Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=12785

Description

In D there are handy associative array literals, so D code contains idioms that are more typical of dynamic languages as Python:


size_t foo(in char c) {
    immutable size_t[char] indexer =
        ['D': 2, 'R': 5, 'C': 8, 'H': 9, 'W': 0];
    return indexer[c];
}


size_t foo(in char c) {
    return ['D': 2, 'R': 5, 'C': 8, 'H': 9, 'W': 0][c];
}


So I suggest to add to D front-end an optimization, that rewrites those usages of associative arrays with a switch:

size_t foo(in char c) {
    size_t value = size_t.max;
    switch (c) {
        case 'D': value = 2; break;
        case 'R': value = 5; break;
        case 'C': value = 8; break;
        case 'H': value = 9; break;
        case 'W': value = 0; break;
        default: assert(false);
    }
    return value;
}


This should be faster, avoid GC activity, and produce simpler binaries.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant