的JavaScript Math.ceil(Math.abs())优化 [英] Javascript Math.ceil(Math.abs()) optimization
本文介绍了的JavaScript Math.ceil(Math.abs())优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用 Math.ceil(Math.abs(X))
在循环中。
任何人都可以实现此操作的最优化? (位还是什么?)
Can anyone realize any optimization for this operation? (Bitwise or what?)
欢迎您在基准 jsperf.com
推荐答案
Math.abs不按的WebKit的JavaScriptCore得不到简单
Math.abs doesn't get simpler according to webkit JavaScriptCore
case MathObjectImp::Abs:
result = ( arg < 0 || arg == -0) ? (-arg) : arg;
但CEIL采用C的ceil函数
However ceil uses C's ceil function
case MathObjectImp::Ceil:
result = ::ceil(arg);
所以测试的JS preF
http://jsperf.com/math-ceil-vs-bitwise
位运算速度更快结果
测试@ orangedog的回答 http://jsperf.com/math-ceil-vs-bitwise/2 数学.ceil更快
so testing on JSpref
http://jsperf.com/math-ceil-vs-bitwise
bitwise is faster
testing @orangedog's answer http://jsperf.com/math-ceil-vs-bitwise/2 Math.ceil is faster
所以我想你最好的选择是:
So I guess your best choice is:
var n = Math.abs(x);
var f = (n << 0),
f = f == n ? f : f + 1;
这篇关于的JavaScript Math.ceil(Math.abs())优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文