I have an bit array var data = []; ...
and I have the following function:
function getBit(n) {
return (data[~~(n / 32)] >> (n % 32)) & 1;
}
Because this is a bottleneck, I need the fastest cross-browser solution in my code, can anybody help make it any faster?
Also, ~~(n / 32)
=== Math.floor(n / 32)
It can be algorithm optimization or syntax optimization (such as asm.js) or something else. Should I change the array type (typedArray
or similar)?
TypedArray
is generally much faster for such things. Have you tried using one and compared speeds? – Mike C Jul 14 '14 at 14:16getBit
(is there a way to process whole words at once more efficiently)? – Cameron Jul 14 '14 at 14:19~~(n / 32) === Math.floor(n / 32)
" Only ifn
isn't negative. ;-) And only ifn / 32
is also <= 32,767 (e.g., won't get truncated when it does its round-trip through being a 32-bit integer). – T.J. Crowder Jul 14 '14 at 14:193
), and seem to simplify based on type information too, probably resulting in the same assembly code for all of the tested versions so far (which is why the timing is so close). – Cameron Jul 14 '14 at 14:50