built-in string hash ?

bearophile bearophileHUGS at lycos.com
Sat Aug 28 18:35:11 PDT 2010


Pelle:
> I doubt that gives any performance gains. typeid(a).getHash should be a 
> constant expression anyway, and I don't see any gains in my tiny 
> benchmark test.

My code shows a limited time difference:

import std.stdio: writeln;
import std.date: getUTCtime, ticksPerSecond;

void main() {
    enum int NLOOP = 30_000_000;
    string s = "and I'd like to add a toHash() member, but I can't find the built-in string hash function.";

    {
        auto t0 = getUTCtime();
        auto stringHash =&(typeid(s).getHash);
        hash_t tot;
        for (int i; i < NLOOP; i++)
            tot += stringHash(&s);
        auto t1 = getUTCtime();
        writeln(tot, " ", (t1 - t0) / cast(double)ticksPerSecond);
    }

    {
        auto t0 = getUTCtime();
        hash_t tot;
        for (int i; i < NLOOP; i++)
            tot += typeid(s).getHash(&s);
        auto t1 = getUTCtime();
        writeln(tot, " ", (t1 - t0) / cast(double)ticksPerSecond);
    }
}


And the asm shows the first loop to contain one less instruction (dmd 2.048, -O -release -inline), so the difference is small:

L42:    lea ECX,01Ch[ESP]
        mov EAX,02Ch[ESP]
        push    ECX
        call    EDI
        add ESI,EAX
        inc EBX
        cmp EBX,01C9C380h
        jb  L42


LA7:    lea EDX,01Ch[ESP]
        mov ECX,_D12TypeInfo_Aya6__initZ
        mov EAX,offset FLAT:_D12TypeInfo_Aya6__initZ
        push    EDX
        call    dword ptr 018h[ECX]
        add EDI,EAX
        inc EBX
        cmp EBX,01C9C380h
        jb  LA7

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list