fizzbuzz

JavaScript performance comparison

Revision 3 of this test case created by Daemonl

Info

Write a program that prints out the numbers 1 to 100 (inclusive).

If the number is divisible by 3, print Fizz instead of the number. If it's divisible by 5, print Buzz. If it's divisible by both 3 and 5, print FizzBuzz.

Preparation code

<p id="title">
  RESULTS
</p>
<p id="results">
</p>
<script>
  function print(val){
      document.getElementById('results').innerHTML += val + ', ';
  }
</script>

Preparation code output

RESULTS

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
no-caching
/*
Written while browsing on iPad using jsPerf with a simple
function to output results to a p element. Syntax would be
equivalent for most C-like languages.

HTML
<p id="title">RESULTS</p>
<p id="results"></p>

Print Function
function print(val){
    document.getElementById('results').innerHTML += val + ', ';
}

*/

for (i = 1; i < 101; i++) {
  if (i % 3 == 0 && i % 5 == 0) print('Fizzbuzz');
  else if (i % 3 == 0) print('Fizz');
  else if (i % 5 == 0) print('Buzz');
  else print(i);
}
pending…
caching
for (i = 1; i < 101; i++) {
  var d3 = i % 3 == 0,
      d5 = i % 5 == 0;
  if (d3 && d5) print('Fizzbuzz');
  else if (d3) print('Fizz');
  else if (d5) print('Buzz');
  else print(i);
}
pending…
Over-the-top DRY
var met, tests, met, txt;
var tests = [
    {test: function(i){return i%3===0;}, message: "Fizz"},
    {test: function(i){return i%5===0;}, message: "Buzz"}];

for (var i = 1; i <= 100; i++) {
    met = false;
    txt = '';
    for(var t = 0; t < tests.length; t++){
        if (tests[t].test(i)){
          txt += tests[t].message;
          met = true;
        }
    }
    if (!met){
       txt += i
    }
    print(txt)
}
 
pending…
Caching, single var
var d3, d5;

for (i = 1; i < 101; i++) {
  d3 = i % 3 == 0;
  d5 = i % 5 == 0;
  if (d3 && d5) print('Fizzbuzz');
  else if (d3) print('Fizz');
  else if (d5) print('Buzz');
  else print(i);
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment