When Bitwise Operations Are Useful In JavaScript
Bitwise operators operate on the individual bits of a variable. Which sounds like a very low level operation for a language like JavaScript, but it does help with performance optimization in some cases. For example, if you are building a color picker that shows the hex as well as RGB formats, you will need to convert between those values. Since there will probably be a way to drag and update the colors, the update will have to occur pretty fast (so it looks smooth to the user). Here is the most obvious algorithm:
var convertHexToRgb = function(hex) { var red = parseInt(hex.slice(0, 2), 16), green = parseInt(hex.slice(2, 4), 16), blue = parseInt(hex.slice(4, 6), 16); return [red, green, blue]; }; console.log(convertHexToRgb('4286f4')); // [ 66, 134, 244 ]
And here is the bitwise based one (adapted from here):
var convertHexToRgb = function(hex) { var rgb = parseInt(hex, 16); var red = (rgb >> 16) & 0xFF, green = (rgb >> 8) & 0xFF, blue = rgb & 0xFF; return [red, green, blue]; }; console.log(convertHexToRgb('4286f4')); // [ 66, 134, 244 ]
In this case the bitwise version is about 4 times faster: https://jsperf.com/hex-color-to-rgb-parseint-vs-bitwise Arguably, there are other ways to increase performance like only update every 50ms, but I needed a very simple example to demonstrate this. There are more complex situations within custom graphics in JavaScript that fast updates are necessary and updating every or near every time is necessary.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/bitwise.js