try...catch slooowness?

spir denis.spir at gmail.com
Sun Dec 19 04:33:29 PST 2010


Hello,


I had not initially noticed that the 'in' operator (for AAs) returns a pointer to the looked up element. So that, to avoid double lookup in cases where lookups may fail, I naively used try...catch. In cases of very numerous lookups, my code suddenly became blitz fast. So that I wondered about exception handling efficiency. Below a test case (on my computer, both loops run in about the same average time):

void main () {
    byte[uint] table = [3:1, 33:1, 333:1];
    byte b;
    byte* p;
    Time t0;
    uint N1 = 246, N2 = 9999999;
    
    // try...catch
    t0 = time();
    foreach (n ; 0..N1) {
        try b = table[n];
        catch (RangeError e) {}
    }
    writefln("try...catch version time: %sms", time() - t0);
    
    // pointer
    t0 = time();
    foreach (n ; 0..N2) {
        p = (n in table);
        if (p) b = table[n];
    }
    writefln("pointer version time: %sms", time() - t0);
    
    writefln("pointer version is about %s times faster",N2/N1);
}
==>
try...catch version time: 387ms
pointer version time: 388ms
pointer version is about 40650 times faster

Note that both versions perform a single lookup trial; the difference thus only lies in pointer deref vs try...catch handling, i guess. What do you think?


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list