FizzBuzz
JavaScript performance comparison
Info
Testing the performance on four variations of the famous "FizzBuzz" test using JavaScript. All four variations use modulus factorials (%) to check against 3 and 5.
The FizzBuzz test: "Write a program that outputs numbers from 1 to 100, except when one of the numbers meets one of three criterial conditions:
1) If a number is a multiple of three, print Fizz instead of the number; 2) If a number is a multiple of five, print Buzz instead of the number; 3) If a number is a multiple of both, print FizzBuzz instead of the number.
The output should look like this: 1 2 Fizz 4 Buzz Fizz ... and so-on.
Preparation code
<script>
Benchmark.prototype.setup = function() {
// recursive `function`
function f(s, n) {
if (++n === 102) return;
s === '' ? console.log(n - 1) : console.log(s); !! (n % 3) ? !! (n % 5) ? f('', n) : f('Buzz', n) : !! (n % 5) ? f('Fizz', n) : f('FizzBuzz', n);
}
// `while` loop
function b(n) {
var i = n;
$: while (++i) {
if (i % 3) if (i % 5) console.log(i);
else console.log('Buzz');
else if (i % 5) console.log('Fizz');
else console.log('FizzBuzz');
if (i >= 100) break $;
}
return;
}
// `for` deductive loop
function F(n) {
var i = n,
f = 'Fizz',
b = 'Buzz',
o = '';
for (; i <= 100; i++) {
o = !(i % 3) ? !(i % 5) ? f + b : f : !(i % 5) ? b : i;
console.log(o);
}
return;
}
// `for` loop
function B(n) {
var i = n;
var fiz = 'Fizz';
var buz = 'Buzz';
for (; i <= 100; i++)
if (!(i % 3)) if (!(i % 5)) console.log(fiz + buz);
else console.log(fiz);
else if (!(i % 5)) console.log(buz);
else console.log(i);
return;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Function : operational, using recursion |
|
pending… |
While : logical, using callbacks |
|
pending… |
For : operational, using deduction |
|
pending… |
For : logical, using callbacks |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
1 comment
Would be interested for someone to test some inverse loops; or to experiment with more readable solutions that are still performant. :)