JavaScript bit Operation notes

Source: Internet
Author: User

It has been thought that in the bit operation of JS, the double-precision floating-point number will be converted into a 32-bit integer, then perform bit operation and then convert to 64-bit value, so the efficiency is very low. Today's experiment found that the bitwise operation on the floating point will only result in inaccurate values, without causing inefficiency, and the left shift is 66% faster than multiplication (in fact, the gap between floating-point and integer operations).

The following results were tested on IE 7 ~ ie 10

Tip 1: The shift operation is faster than the multiplication method (when the factor is a power of 2)

b = a << 1; // probably fast 6.8% .


Tip 2: Parity and even judgment

b = A & 1; // 0-bit vs. 1 phase, approximately 35% compared to x 2

Tip 3: Determine if the two-digit symbol is the same

 (a ^ b) >= 0//  compared to  if  (A = = 0)  return  1; else  if  (A > 0)  return  b >= 0;  else  return  b <= 0;  //  its efficiency is basically the same, but more concise.  //  compared to   * b) >= 0;  //  There is no overflow problem. 


Tip 4: Determine if a number is a power of 2

(A & (a-1)) = = 0;

JavaScript bit Operation notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.