3 ms·
All of the difference comes from 1) inlining and 2) avoiding the alignment test. Once you adjust for that it's actually slower. Regardless of alignment penalti
by wahern 10y ago
All of the difference comes from 1) inlining and 2) avoiding the alignment test. Once you adjust for that it's actually slower.
Regardless of alignment penalties, memcmp always needs to test for alignment so that it doesn't read past the end of a page, causing a segfault. This hack isn't appropriate for general purpose use; only where you know for sure an unaligned read won't overflow a page boundary.
- feelix 10y agoIt checks that it wont overflow beforehand by making sure the length is >= 4 (and it's still faster). And I'm not sure why you think inlining would result in the speed increase? I believe the compiler will inline it when the standard memcmp is used too.
- wahern 10y agoYou're right about the page overflow. Sorry. Regarding inlining, using GCC 6.2 with "-O3 -march=native" on macOS I first had to remove "111111" and "222222" as constants, otherwise GCC precomputed both loops. When I used __attribute__((noinline)) on mycmp, half of the difference went away. When I forced mycmp to check the alignment, mycmp became slower by almost a full second. That was on a 2011 Mac Mini. Using a newer box with a Haswell chip (Xeon E3-1230 v3) and GCC 5.4.0 performance is about the same when preventing inlining and adding the alignment check, rather being slower. In both cases the assembly confirms that neither mycmp nor memcmp were inlined.