Randall's example is more interesting because it shows that
a<<b is equivalent to a * Math.pow(2, b). As someone already
said, bit shifts are a very simple operation and will be
faster than multiplying or dividing by multiples of 2.
<snip>
The obvious next question is; if faster then by how much? So I created
some test pages to find out.
Comparing - Math.floor(S/2) - with - (S>>1) - seemed a reasonable
starting point. There are some differences as Math.floor rounds negative
numbers downwards while the shift moves them towards zero and the result
of the shift is a 32 bit signed integer so it cannot represent the same
integer range as the IEEE float that Math.floor outputs. The test page
is:-
<URL:
http://www.litotes.demon.co.uk/js_speed/intDivBy2.html >
- and produced the results (taking Math.floor(S/2) as 100% on all tested
browsers for comparison):-
Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
Math.floor(n/2) -- -- 100% -- --
(n>>1) 7.18% 22.94% 8.60% 16.28% 16.93%
Making the shift operation between 4 and 14 times faster.
That seemed a reasonable start so I compared - Math.floor(n)*2 - and -
(n<<1) :-
<URL:
http://www.litotes.demon.co.uk/js_speed/intMulBy2.html >
- getting the results:-
Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
Math.floor(n)*2 -- -- 100% -- --
(n<<1) 8.03% 21.82% 8.46% 26.19% 26.80%
Generally worse but not by much.
Looking at the above tests it occurred to me that any bitwise operator
was going to have the a similar effect to Math.floor (when the internal
ToInt32 function is called) if its input was a positive integer <= 31
bits, as might be the case when calculating screen co-ordinates with
floats and then converting the results to pixel co-ordinates. So any
bitwise operation that would not alter a 32 bit integer may be
substituted for Math.floor for those cases:-
<URL:
http://www.litotes.demon.co.uk/js_speed/floorMethods.html >
Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
Math.floor(n) -- -- 100% -- --
(n&0xFFFFFFFF) 14.40% 29.54% 14.42% 52.03% 24.25%
(n<<1)>>1 10.97% 56.04% 19.86% 39.70% 43.49%
(n|0) 8.23% 29.02% 10.64% 33.84% 24.33%
The double shift did not strike me as a good candidate as it further
reduces the maximum size of the integer (and involves two operations)
but as it performed generally badly it can be dismissed for that reason
alone (though I was surprised that it outperformed bitwise AND on
Mozilla 1.2). The bitwise OR zero operation is the clear winner at
between 3 and 12 times faster than Math.floor. Not a complete substitute
but if enough is known about the input it could be a fast alternative in
some cases.
Richard.