S
Stephen Sprunk
Stephen Sprunk said:Well, other things can be extremely fast too. Compilers can
optimize the p[0] + 256*p[1] example I gave in one of the
earlier threads, and I wouldn't be surprised if someone told me
they already do.
I've seen GCC on x86 recognize and replace the shift/or idiom with
a load (and byteswap, if applicable). It might also
strength-reduce the multiply/add version and then recognize the
idiom, but the code would be clearer to human readers if you used
the idiom in the first place; that's the point of idioms.
I'm puzzled as to why Jorgen's expression isn't idiomatic as it
stands.
p[0] + 256 * p[1]
p[0] + (p[1] << 8)
p[0] | p[1] << 8
Is any one of these more or less idiomatic than the others?
The third one is idiomatic; the others are not, even if they likely
produce the same result.
That aside, the latter two should be faster if the compiler does
nothing clever.
That's probably part of why it became the idiomatic form: it dates from
back before compilers had optimizations like strength reduction.
Beyond that, byte shuffling is obviously a bitwise operation, not an
arithmetic one, so bitwise operators seem more appropriate anyway.
S