Exotic add function in JavaScript
JavaScript performance comparison
Info
Comparison between add functions. View the gist here
Preparation code
<script>
Benchmark.prototype.setup = function() {
function add_normal() {
// Start from zero
var total = 0;
// Floating-points, bah!
// 1e12 = 1000000000000.
var factor = 1e12;
// Undefined, set in the loop
var value;
// Something to iterate on
var i = arguments.length;
// Loop through all the parameters
while (i--) {
// Multiply by 1e12, to account for peculiarities
// of doing addition with floating-point numbers.
value = parseFloat(arguments[i]) * factor;
// Is it not, not a number?
// Then hey, it's a number!
if (!isNaN(value)) {
total += value;
}
}
// Divide back by 1e12, because we multiplied by
// 1e12 to account for floating-point weirdness.
return total/factor;
}
// can you figure it?
function add_exotic() {
var args = [].slice.call(arguments), total = 0;
for (;args.length; args.shift()) {
!args[0] || typeof args[0] === 'boolean' || (total += parseFloat( !(args[0]*1) ? 0 : args[0] ) * 1e12);
}
return total/1e12;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Add normal |
|
pending… |
Add exotic |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments