开发者

Faster than memcmp

I have a UUID class that has an inbuilt 16 byte buffer for the UUID.

The >, <, ==, != overloaded operators just call memcmp() over the 16 byte value.

Since this class is going to be used on a 64-bit architecture only, would it be faster to compare the 128 bits using two 64-bit ints instead?

e.g. Instead of:

memcmp(uuid1, uuid2, 16) == 0

Can I just do something like:

unsigned long* id1 = (unsigned long*)uuid1;
unsigned long* id2 = (unsigned long*)uuid2;
bool equal = (id1[0] == id2[0] && id1[1] == id2[1]);

Or does the memcmp() functi开发者_运维技巧on used by G++ do this kind of optimisation already? On the other hand, not using memcmp() will avoid the function call overhead yes?


With today's processors, there's a very good chance that the comparison is limited by the speed of fetching the bytes from memory. The comparison itself will likely be in parallel with it, whether it's byte by byte or 64-bit by 64-bit. The only way to be sure is to benchmark it.

As for the call overhead, it's quite possible that memcmp is implemented as an intrinsic function with no overhead at all. Check the generated assembly listing to be sure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜