哪个更快:Math.abs(value)或value * -1? [英] Which is faster: Math.abs(value) or value * -1 ?

查看:58
本文介绍了哪个更快:Math.abs(value)或value * -1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相当简单,但是我只想知道哪个更快.

Pretty straightforward, but I just want to know which is faster.

我认为,只要确定值是负数,简单地将数字乘以 -1 就会比调用预定义方法快得多.

I think simply multiplying a number by -1 is much faster than calling a predefined method, provided that you are sure that value is negative.

但是如果是这种情况,那么 abs()函数的作用是什么?仅仅是为了确保无论值的符号如何,返回的值始终为正吗?

But if that's the case then what is the abs() function for? Is it simply for making sure that the value returned would always be positive regardless of value's sign?

推荐答案

2012年8月更新:

我对这些实现进行了分析:

I did some profiling with these implementations:

/* Test 1: */ b = Math.abs(a);
/* Test 2: */ b = abs(a); //local copy: abs = Math.abs;
/* Test 3: */ b = a < 0 ? a * -1 : a;
/* Test 4: */ b = a < 0 ? -a : a;

在Windows 7上,我得到以下结果.每个浏览器最快的结果后,值均被标准化,以便更轻松地比较哪种方法更快:

I got the following result on Windows 7. Values are normalized after the fastest result per browser to make it easier to compare which method is faster:

        1:Math 2:abs 3:*-1  4:-    1.0=   Version
Chrome    1.0   1.0   1.0   1.0    111ms  21.0.1180.75 m
Firefox   1.0   1.0   1.2   1.2    127ms  14.0.1
IE        1.4   1.0   1.1   1.0    185ms  9.0.8112
Opera     1.9   1.6   1.1   1.0    246ms  12.00
Safari    1.6   1.6   1.1   1.0    308ms  5.1.7

结论:3年前,当我进行此测试时,-a最快,但是现在在Firefox中Math.abs(x)更快!在Chrome中, abs(a) -a 获得了相同的时间,而当我用1000万个数字对其进行测试时,最慢的方法仅相差3毫秒.

Conclusion: When I did this test 3 years ago, -a was fastest, but now Math.abs(x) is faster in Firefox! In Chrome abs(a) and -a got the same time and it was only 3 ms difference to the slowest method when I tested it with 10 000 000 numbers.

我的推荐:使用 Math.abs(a).如果您处于紧密循环中,并且通过分析发现它太慢,则可以对abs函数使用本地引用:

My Recommendation: Use Math.abs(a). If you are in a tight loop and by profiling has found it to be too slow, you can use a local reference to the abs function:

var abs=Math.abs; //A local reference to the global Math.abs function
for (i=0;i<1234567890;++i) if ( abs( v[i] ) > 10) ++x;

这篇关于哪个更快:Math.abs(value)或value * -1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆