Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cube is faster than square

I wrote this:

  var max = 0xffffff * 4;   var step = 1 / max;   function cube() {     var result = 0.;     for (var x = 0.; x < 1; x += step) {       result += x * x * x;     }     return result;   }   function mul() {     var result = 0.;     for (var x = 0.; x < 1; x += step) {       result += x * x;     }     return result;   }   function go() {     var r = '';     r += cube() + ' \n';     r += mul() + ' \n';     alert(r);   } 

and see the result in Chrome profiler:

mul: 106ms  cube: 87ms 

How is that possible?

like image 659
shal Avatar asked Mar 23 '16 12:03

shal


1 Answers

Your assertion is plain wrong. cube is not faster than mul and your example does not prove it.

In fact, what happens is that the internals of Javascript execution take more time than the actual multiplication, resulting in very similar times for mul and cube. I ran the two functions in a loop, just to increase the difference and the profiler shows 20219 vs 20197, which is insignificant. And BTW, cube is the "slower" one here.

Moreover, this method of profiling doesn't work because both Chrome and Firefox are optimizing a lot before doing maths inside loops. What you think is a loop may very well use a cached value or even a mathematical function that the optimization knows returns the same result.

Here is the code I used:

<script>  var max = 0xffffff * 4;   var step = 1 / max;   function cube() {     var result = 0.;     for (var x = 0.; x < 1; x += step) {       result += x * x * x;     }     return result;   }   function mul() {     var result = 0.;     for (var x = 0.; x < 1; x += step) {       result += x * x;     }     return result;   }   function go() {     var s='';     for (var i=0; i<100; i++) {         s+=cube();         s+=mul();     }     console.log(s);   }   go(); </script> 

Also, as a reference only, watch the video here: https://fosdem.org/2016/schedule/event/mozilla_benchmarking_javascript_tips/ where a Firefox guy explains why microbenchmarking doesn't really mean much.

like image 145
Siderite Zackwehdex Avatar answered Sep 23 '22 01:09

Siderite Zackwehdex