Your statement is incorrect. a cube is no faster than a mul, and your example does not prove it.
In fact, what happens is that the internals of Javascript take longer than the actual multiplication, which leads to very similar times for mul and cube. I ran two functions in a loop, just to increase the difference, and the profiler shows 20219 versus 20197, which is insignificant. And BTW, the cube here is "slower."
In addition, this profiling method does not work because both Chrome and Firefox optimize a lot before doing the math inside loops. What you think is a loop, it can very well use a cached value, or even a mathematical function that 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, watch the video here: https://fosdem.org/2016/schedule/event/mozilla_benchmarking_javascript_tips/ , where a guy from Firefox explains why microdetection really doesn't mean much.
Siderite Zackwehdex Mar 29 '16 at 8:12 2016-03-29 08:12
source share