引用这篇文章: math-round-vs-hack
我们优化了数学函数。
我们使用 (num+0.5)|0
而不是 Math.round()
。
但是有一个问题让人很困惑,当num > 2147483647时,结果是错误的。
function round(n) {
return (n + 0.5) | 0;
};
round(2147483648)
将返回 -2147483648
根据维基百科:
2147483647 in computing
The number 2,147,483,647 is also the maximum value for a 32-bit signed integer in >computing. It is therefore the maximum value for variables declared as int in many >programming languages running on popular CPUs, and the maximum possible score (or amount >of money) for many video games. The appearance of the number often reflects an error, >overflow condition, or missing value.[8] Similarly, "(214) 748-3647" is the sequence of >digits represented as a United States phone number and is the most common phone number >listed on web pages.[9] The data type time_t, used on operating systems such as Unix, is a 32-bit signed integer >counting the number of seconds since the start of the Unix epoch (midnight UTC of 1 >January 1970).[10] The latest time that can be represented this way is 03:14:07 UTC on >Tuesday, 19 January 2038 (corresponding to 2,147,483,647 seconds since the start of the >epoch), so that systems using a 32-bit time_t type are susceptible to the Year 2038 >problem.[11]
我该如何处理这种情况以确保良好的性能?
最佳答案
简答:使用 Math.round()
我会将整个练习归档在“为什么你永远不应该进行微优化”下。看看这个 fiddle :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:round 399ms,bit_round 32ms(1000000 次迭代)
当然,在最好的情况下,按位舍入函数比使用 Math.round() 快得多,但这真的重要吗?最坏的情况 Math.round() 仍然处理数百万轮 pr。秒没有问题。
您需要进行多少次舍入?我不希望你在 javascript 中对数字进行四舍五入,除了显示数字,即使你要显示数千个四舍五入的数字 pr。其次,Math.round() 对您来说仍然足够快。
更新
此外,关于一般的微优化,请务必查看来自 Coding Horror 的文章:http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html
微优化很少是个好主意。
关于javascript - 当 num > 2147483647 时按位或导致溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10205503/