class templates and static if

Dmitry Olshansky dmitry.olsh at gmail.com
Tue Feb 28 02:12:40 PST 2012


On 28.02.2012 2:17, Ali Çehreli wrote:
> On 02/27/2012 02:06 PM, Jonathan M Davis wrote:
>
>  > I'm not saying that dmd doesn't ever optimize switch statements. I'm
> just
>  > saying that as I understand it, it doesn't always do so (its
> performance with
>  > ranged case statements isn't great for instance). Odds are that it
> _does_
>  > optimize straight integer case statements fairly well, because that's
> the
>  > classic C stuff (and if you've verified that, all the better - I
> haven't).

I would say use switch when you have multiple choises over one variable, 
because the compiler *can* do much better job then with if/else chain 
(even for strings, e.g. hashing, same binary-search approach). Because 
the if/else chain fixes the order of comparisons it can't become faster 
at all (or it would be an aggressive optimization).
It's just wrong idea to lose this opportunity with switch.

>
> I have played with this optimization recently. (Could be dmd 2.057.) No,
> dmd did not optimize a straightforward switch statement over a ubyte
> expression with about two hundred ubyte cases.
>
Hate to say it but I see it in real-world code, VM performance almost 
doubled. Mm care to share you experiments? Alternatively just dissemble 
any regex sample, seek out mangled trash of _xxx_eval_xxxx function.

> The assembly contained conditional jump statements, not a table. And
> yes, I did try with -O.
>
> But I am not sure that a lookup table really is an optimization with
> modern CPUs. A series of conditional jumps that fit the CPU's cache
> could be faster than a table that's outside of the cache. I think
> accessing the cache is hundreds of times faster than accessing memory
> outside of the cache.

It's all about branch prediction really - hundreds of cmp xxx je xxx 
stall pipelines pretty darn well. Though the effect might depend on the 
code size inside these case branches.
BTW tables should be somewhere close, though I haven't checked this.

-- 
Dmitry Olshansky


More information about the Digitalmars-d-learn mailing list