Bitwise or cause overflow when num> 2147483647

Refer to this article: math-round-vs-hack

We have math functions optimized.

We use (num+0.5)|0instead Math.round().

But there is a problem that confuses the fact that when num> 2147483647, this leads to incorrect results.

function round(n) {
    return (n + 0.5) | 0;
};

round(2147483648) will return -2147483648

And according to wikipedia:

2147483647 when calculating

The number 2,147,483,647 is also the maximum value for a 32-bit signed integer in> calculations. Therefore, this is the maximum value for variables declared as int in many programming languages ​​running on popular processors, and the maximum possible amount (or amount of money) for many video games. The appearance of a number often reflects an error, an overflow condition, or a missing value. [8] Similarly, “(214) 748-3647” is a sequence of numbers> represented as a phone number in the United States of America, and is the most common phone number> indicated on web pages. [9] The time_t data type used on operating systems such as Unix is ​​a 32-bit signed integer>counting the number of seconds since the start of the Unix era (midnight UTC 1> January 1970). [10] The last time that can be represented in this way is 03:14:07 UTC on> Tuesday, January 19, 2038 (corresponding to 2,147,483,647 seconds from the beginning of the era), so systems using the 32-bit type time_t susceptible to the problem of 2038. [eleven]

, ?

+3
1

: Math.round()

" ". : http://jsfiddle.net/toxicsyntax/a5rWm/2/

:

  • Firefox 11: round: 185ms bit_round: 123ms ( 100000000 )
  • Chrome 18: round: 99ms bit_round: 96ms ( 100000000 )
  • IE 9: round: 227ms bit_round: 123ms ( 1000000 )
  • IPhone 4, Safari: 399ms, _round 32ms ( 1000000 )

, , Math.round(), ? Math.round() pr. .

? , - javascript, , pr. -, Math.round() .

Update

, , Coding Horror: http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html

, .

+3

All Articles