D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 12785 - Optimize with switches some associative array usage idioms
Summary: Optimize with switches some associative array usage idioms
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2014-05-21 23:23 UTC by bearophile_hugs
Modified: 2024-12-13 18:20 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2014-05-21 23:23:00 UTC
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.
Comment 1 dlangBugzillaToGithub 2024-12-13 18:20:49 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/17660

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB