1

At the first lines of Asm.js definition there's a Asm.js-based code example that explains the bitwise operation helps to have a faster JS code:

HEAP32[p >> 2]|0

or

(x+y)|0

My question is, how this operation boost the performance and what's the reason behind using this bitwise operator many times in Asm.js or Emscripten-generated JS codes?

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201

2 Answers2

2

The bitwise operators force their operands to be integer values. It's a considerably faster way of doing the conversion than calling Math.floor, etc. Note that

p >> 2

is (for non-negative values of p) the same as Math.floor(p / 4).

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

Using a right bit shift (>>) by 1, is the same as dividing by 2, but it is faster than actually calculating it base 10 because the computer can just shift the binary digits in memory without having to do a calculation. It's just like in base 10 when you want to multiply a number by 10, you know you can just add a zero to the right side of the number (The reverse, division, would be taking the zero off of the right side). So, by shifting right two digits you are dividing by 2 twice (e.g. 24/2 = 12 and 12/2 = 6 or 24/4 = 6)

Apparently, (x+y)|0 is just a faster way to do a floor.

Community
  • 1
  • 1
Alex W
  • 37,233
  • 13
  • 109
  • 109