String compare in words?

Seb via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 29 13:51:19 PDT 2016


On Sunday, 29 May 2016 at 20:40:52 UTC, qznc wrote:
> On Sunday, 29 May 2016 at 18:15:16 UTC, qznc wrote:
>> [...]
>
> Ok, to answer my own question, this looks good:
>
> bool string_cmp_opt(immutable(ubyte)[] x, immutable(ubyte)[] y) 
> {
>     pragma(inline, false);
>     if (x.length != y.length) return false;
>     int i=0;
>     // word-wise compare is faster than byte-wise
>     if (x.length > size_t.sizeof)
>         for (; i < x.length - size_t.sizeof; i+=size_t.sizeof) {
>             size_t* xw = cast(size_t*) &x[i];
>             size_t* yw = cast(size_t*) &x[i];
>             if (*xw != *yw) return false;
>         }
>     // last sub-word part
>     for (; i < x.length; i+=1) {
>         if (x[i] != y[i]) // byte compare
>             return false;
>     }
>     return true;
> }
>
> Any comments or recommendations?

Isn't that something that the compiler should optimize for you 
when you do an equality comparison?
Is it really faster than ldc (with all optimzations turned on)?


More information about the Digitalmars-d-learn mailing list