请参阅本文:
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()
我将在“为什么永远不进行微优化”下进行整个练习.看看这个小提琴:http://jsfiddle.net/toxicsyntax/a5rWm/2/
这是来自不同浏览器的一些结果:
> Firefox 11:舍入:185ms位_舍入:123ms(用于100000000次迭代)
> Chrome 18:圆形:99毫秒位_圆形:96毫秒(用于100000000次迭代)
> IE 9:回合:227ms bit_round:123ms(用于1000000次迭代)
> iPhone 4,Safari:圆形399ms,bit_round 32ms(用于1000000次迭代)
当然,在最佳情况下,按位舍入函数比使用Math.round()快得多,但这真的重要吗?最坏的情况是Math.round()仍然处理数百万轮.秒没有问题.
您必须进行四舍五入?我不希望您会在javascript中舍入数字,除了显示数字,即使您正在显示成千上万的数字也是如此.其次,Math.round()仍然对您足够快.
更新资料
而且,对于一般的微观优化,请务必查看Coding Horror的文章:http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html
微观优化很少是一个好主意.