Hacker News new | ask | show | jobs
by ConceptJunkie 86 days ago
> The same trick can also be used for the other direction to save a division:

> NewValue = OldValue >> 3; > This is basically the same as

> NewValue = OldValue / 8;

> RCT does this trick all the time, and even in its OpenRCT2 version, this syntax hasn’t been changed, since compilers won’t do this optimization for you.

The author loses a lot of credibility by suggesting the compiler won't replace multiplying or dividing by a factor of 2 with the equivalent bit shift. That's a trivial optimization that's always been done. I'm sure compilers were doing that in the 70s.

2 comments

I wouldn't go that far, but yes, no compiler will leave that on the table today or even twenty years ago. They do even more impressive transformations than that on basic math.
The author is partly right here. If those values are ints, you'll get something like this:

  sar eax, 0x1f
  and eax, 7
  add eax, edx
  sar eax, 3
You get 4 instructions instead of one because value >> 3 rounds towards negative infinity and value / 8 rounds towards zero.

And while this wouldn't apply to C++, in languages with checked arithmetic, the left shift won't necessarily set the overflow flag, so the compiler often can't use it.