JavaScript性能-除还是乘?/vs * [英] JavaScript Performance - Divide or Multiply? / vs *

查看:30
本文介绍了JavaScript性能-除还是乘?/vs *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个JavaScript非常繁重的应用程序(几乎所有JavaScript),并且确实有大量数据要迭代(JSON),并且必须执行某些算术任务.性能是应用程序的主要考虑因素.我已经介绍了Webworkers来帮助解决这个问题,并且我试图不退缩由jQuery之类的库提供的方法(例如 .each()而不是 for 循环).无论如何,这是一个简单的问题...

I'm writing an application that is very JavaScript heavy (it's pretty much all JavaScript) and it does have a considerable amount of data to iterate through (JSON) and with this it must perform arithmetic certain tasks. Performance is a major consideration of the application. I have introduced Webworkers to help with this and I am trying not to fall back on methods provided by libs like jQuery (like .each() instead of for loops). Anyway, here's a simple question...

在应用程序中,我必须应用价格更改,这将涉及很多涉及除法的数值过程.除非这会成千上万次发生,否则对我而言,总是通过乘法或乘法与除法的混合来应用更改会更好.例如,我可以通过乘以0.5或除以2来获得50%的折扣.

Within the application I have to apply price changes which will involve alot of numerical processes involving dividing. Baring in mind this will happen thousands and thousands of times would it be better for me to always apply a change by multiplication or a mixture of multiplication and division. For example I can apply a 50% discount by multiplying by 0.5 or dividing by 2.

我总是被告知除法比乘法要慢,但是我没有真正的证据……在开始进行基准测试和运行测试之前,有人对此有意见吗?

I was always taught that division is slower than multiplication but I have no real proof of this… has anyone got an opinion on this before I start benchmarking and running test?

推荐答案

尽管这两个操作都非常快,但是乘法的性能要比除法好一些.在下面的测试中,我注意到Chrome上的差异为14%,IE 9上的差异为10%.如果您必须从浏览器中压缩性能,则可以在输入之前将除法器转换为乘数循环,但我认为将可读性折衷为如此小的改进不是一个好主意.

Although both operations as very fast, multiply has a slightly better performance than the divide. In my tests (below), I noticed a 14% difference on Chrome and 10% difference on IE 9. If you must squeeze that performance from the browser, you can transform the divider to a multiplier before entering loops, but I don't think it is a good idea to compromise readability to such a tiny improvement.

var cnt = 500000;
var rls = []
var ags = [[2,1], [4,2], [7,3], [4e0,1], [32e0,2], [37e0,3], [-37e7,(7e3/3e-4)]];
var fns = [
  {name: "fn_mul", fn: (function(x, y) { return x * y; })},
  {name: "fn_div", fn: (function(x, y) { return x / y; })}
]

// setup  ---------------------------------------
for(var iag=0; iag<ags.length; iag++) {
  if(Object.prototype.toString.call(ags[iag]) !== "[object Array]") {
    ags[iag] = [ags[iag]]
  };
}

// run ------------------------------------------
for(var ifn=0; ifn<fns.length; ifn++) {
  var fn = fns[ifn].fn;
  var ts = (new Date()).valueOf();
  for(var iag=0; iag<ags.length; iag++) {
    var ag = ags[iag];
    for(var icn=0; icn<cnt; icn++) { fn.apply(this, ag); }
  }
  rls.push({"name": fns[ifn].name, "ts": (new Date()).valueOf() - ts});
}
dump(rls);

这篇关于JavaScript性能-除还是乘?/vs *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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