nevets
nevets

Reputation: 4818

Efficiency of bitwise operation in Javascript

According to w3schools

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

So my question comes: if we want to perform a bitwise operation, how javascript translates that 64-bit IEEE 754 standard float to an ordinary 32-bit integer, and how efficient it is? From intuition, converting numbers will be costly, so will it still be more efficient to use bit shifting than multiply by 2n?

Thank you very much!

Upvotes: 1

Views: 2092

Answers (1)

Jimmy Breck-McKye
Jimmy Breck-McKye

Reputation: 3034

From The Good Parts:

Bitwise operators work with integers. JavaScript doesn't have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow.

Ultimately, though, the behavior will nearly always be implementation-specific. Some JavaScript environments may - today or in the future - be able to reason that this-or-that piece of code will always be handled like an int, or perhaps store vars as ints by default.

The only way to know for sure is to profile your code. A tool like JSPerf might be helpful. It might also give you contradictory metrics - what runs faster in one browser might perform poorly in another JavaScript engine. Performance gains might also depend on heuristics that your own production code unknowingly breaks.

The real question, though, is a different one: what are you planning to do that makes multiplication performance a critical factor in performance? Because it's probably not something you should be doing in a UI-blocking client side script.

Upvotes: 4

Related Questions