On Sunday, 29 May 2016 at 18:15:16 UTC, qznc wrote:
On Sunday, 29 May 2016 at 17:38:17 UTC, Jonathan M Davis wrote:
And if you're not simply comparing for equality, what are you
looking to figure out? Without more information about what
you're trying to do, it's kind of hard to help you.
If I write the comparison naively, the assembly clearly shows a
"movzbl" [0]. It loads a single byte! The other single byte
load is encoded in the address mode of "cmp". Implementation:
bool stringcmp(string x, string y) {
foreach(i; 0..x.length) {
if (x[i] != y[i]) // byte compare
return false;
}
return true;
}
It makes no sense to load single bytes here. Since we only want
to check for equality, we could load two full words and compare
four or eight bytes in one go.
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?