Debunk division by multiplication

JavaScript performance comparison

Test case created by Raymond

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
"slow"
var my_variable = 5 / 2;
pending…
"fast"
var my_variable = 5 * 0.5;
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

2 Comments

Miller Medeiros commented :

Browsers are smart, behavior might change based on the condition, see this perf test: http://jsperf.com/multiply-vs-divide/3

And read more about what might be going on this test: http://blog.millermedeiros.com/benchmarking-is-hard/ - TL;DR; JIT and caching are giving misleading results in this case.

I'm not saying you should always use division, I've seen different behavior based on browser and usage. This is probably a "premature optimization" unless you need to do something over an insane amount of data (eg. processing pixels on a large image).

Always profile your code and make sure it does apply to your use case. Also make sure your perf tests aren't biased.

Cheers.

Blade commented :

FDIV is always more expensive than multiply, unless you have hardware specialized for fdiv.