19

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...

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?

Mike Sav
  • 14,805
  • 31
  • 98
  • 143

3 Answers3

72

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);
Gerardo Lima
  • 6,467
  • 3
  • 31
  • 47
  • 31
    Thank you SO much for simply *answering the question*, rather than telling everyone what we already know. This should be the chosen answer, imo. – Shea Sep 08 '13 at 06:03
  • http://pt.stackoverflow.com/questions/10909/por-que-multiplicacao-e-mais-rapido-que-divisao – Sergio Mar 28 '14 at 12:41
  • It all depends where you code is running. If the speed of the device (mobile or embedded) isn't all that fast it does matter. Especially if it needs to be done several times a second for each rendered frame. Thank you for the good example and direct answer. – CaptainBli May 08 '17 at 21:41
  • Not exacly, @CaptainBli, the bottleneck will most likely always be the DOM manipulation (or any other API for rendering UI). It would make a noticeable difference, though, when a big number of interactions are necessary between each UI refresh, like on calculation intensive libraries. In other cases I would not recommend trading readability -- please notice that browsers are now much better than when I wrote this answer and such optimization can be part of the JIT compilation process now. – Gerardo Lima May 09 '17 at 16:14
  • 1
    My browser is a Webkit Qt4 browser running on limited hardware (ARM single core). You are correct that the biggest issue is to reduce DOM manipulations, and every cycle counts. Your tests helped show that our system needs optimization over readability. Luckily we can put comments in the code to help understand as they do get removed on compactification. – CaptainBli May 09 '17 at 17:43
  • 2
    How this isn't the preferred answer, I have no idea. Solid answer @GerardoLima – stetson Nov 19 '19 at 15:59
  • Does this still hold true, after a decade? – Константин Ван Feb 28 '22 at 08:20
  • 1
    yes, @КонстантинВан, I just ran this code on my computer and multiplication is about 6% faster than division -- I run the tests on NodeJs 16, in a MacBook Pro; I had to multiply the counter `cnt *= 100`, for the difference to be perceptible – Gerardo Lima Feb 28 '22 at 10:39
  • 1
    Again, I wouldn't recommend making the code _less obvious_ in favour of such small improvement. If your problem is performance, there should be other more obvious places to look for, before entering into this minefield -- DOM manipulation, network calls, _costly_ synchronous code blocks, ... – Gerardo Lima Feb 28 '22 at 10:43
  • 1
    https://jsbench.me/2al2oytoko/1 Shows the division about 50% slower than multiplication. – pailhead May 02 '22 at 16:59
9

To add a bit more context to this, provided that the compiler does not optimize divisions to multiplications (e.g. n / 2 gets converted to n * 0.5), multiplications are always going to be faster than divisions.

This is due to how these operations are performed by the CPU:

See https://stackoverflow.com/a/1148060/520857 for reference to x86 (spoiler: fmul is 2-3x faster than fdiv)

See https://stackoverflow.com/a/17883319/520857 for reference to AMD (spoiler: fmul is 7x faster than fdiv)

The speeds of these operations are too fast to matter much IRL, but if you're doing a lot of them and you find that the compiler is not converting to multiplication (I don't think javascript engines do this, don't quote me on it though, a quick google check didn't give me any info on the topic), then it might make sense to make this optimization if you're encountering performance bottlenecks caused by divisions being too slow, which unlikely as you're more likely to be I/O bound than CPU bound in almost all applications.

edit: If you're performing lots of floating point calculations, you can consider finding a way to use your GPU to perform those operations as GPUs are significantly faster at FP ops than CPUs, to start you off from a quick google search again: http://gpu.rocks/

Populus
  • 7,470
  • 3
  • 38
  • 54
0

Personally I don't think it makes much difference in terms of performance. You're getting right down to a micro level if you're considering this.

Readability of your code is much more important than a micro optimisation like this. Code for readability and ease of understanding and if you absolutely must micro-optimise, do that later when you've found your real bottlenecks.

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162