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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With