1

In C++, What is the most efficient way (memory and timing) to compare two structs of word size (eg. size of 4 Bytes in 32 bit architecture). assume no garbage padding bits and:

struct A, B;

on one hand, I can use

memcmp(&A, &B, 4)

on the other hand, I can write

struct *pA = &A; struct *pB = &B;

if (*pA == *pB)

thanks

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Haim Itzhayek
  • 181
  • 2
  • 9
  • 2
    You probably shouldn't be bothered, unless you have explicit indication that this comparison is causing a bottle-neck in existing code. If you do have this indication, it should be trivial to try each and see which is faster. – TripeHound May 16 '16 at 10:47
  • Is your question about C or C++? In C++ the comparisons aren't the same. `memcmp` does a byte-wise compare (and is technically C, not C++). Comparing members on the other hand invokes `operator==`, which does whatever it is defined to do (which can be a `memcmp` as well). If it's not defined it is a compiler error. – Stjepan Bakrac May 16 '16 at 10:50
  • 2
    if (*pA == *pB) this is same as if (A == B) – bashrc May 16 '16 at 10:52
  • Possible duplicate of [Should I use memcmp or chained equal-to operations when both give the same result?](http://stackoverflow.com/q/28858359) – Emil Laine May 16 '16 at 20:54

1 Answers1

8

It depends.

It depends on the library and the compiler ... and perhaps the target platform. If this is a performance bottleneck, the only way to find the most efficient is to write both and compare their efficiency.

If it isn't a performance bottleneck (and it won't be), just write the simplest, clearest, easiest to understand code. Which is:

    if (A == B)

(not to mention that the above code doesn't have to make any assumptions about padding bits).