Calculating Length of Month

JavaScript performance comparison

Revision 5 of this test case created by

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var sink;
  
  var staticLookup = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

};

Benchmark.prototype.teardown = function() {
  if (sink > 31) throw new Error();

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Curtis McEnroe's Method
function f(x) {
  return 28 + (x + Math.floor(x / 8)) % 2 + 2 % x + 2 * Math.floor(1 / x);
}

for (var i = 1; i < 12; i++) {
  sink = f(i);
}
pending…
Bitwise Method
function f(x) {
  var y;
  return (y = 30 | (x >> 3 ^ x) & 1) ^ (~(x >> 2 | x | y) & 1) << 1
};

for (var i = 1; i < 12; i++) {
  sink = f(i);
}
pending…
Lookup Method
function f(x) {
  var y = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  return y[x];
}

for (var i = 1; i < 12; i++) {
  sink = f(i);
}
pending…
Lookup (Global Table)
var y = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

function f(x) {
  return y[x];
}

for (var i = 1; i < 12; i++) {
  sink = f(i);
}
pending…
Lookup (Bitwise, Padded)
function f(x) {
  return 28 | (0x3BBEECC >> x >> x) & 3;
}

for (var i = 1; i < 12; i++) {
  sink = f(i);
}
pending…
Switch Method
function f(x) {
  switch (x) {
    case 1:
      return 31;
    case 2:
      return 28;
    case 3:
      return 31;
    case 4:
      return 30;
    case 5:
      return 31;
    case 6:
      return 30;
    case 7:
      return 31;
    case 8:
      return 31;
    case 9:
      return 30;
    case 10:
      return 31;
    case 11:
      return 30;
    case 12:
      return 31;
  }
}

for (var i = 1; i < 12; i++) {
  sink = f(i);
}
pending…
If Method
function f(x) {
  if (x === 1) x = 31;
  else if (x === 2) x = 28;
  else if (x === 3) x = 31;
  else if (x === 4) x = 30;
  else if (x === 5) x = 31;
  else if (x === 6) x = 30;
  else if (x === 7) x = 31;
  else if (x === 8) x = 31;
  else if (x === 9) x = 30;
  else if (x === 10) x = 31;
  else if (x === 11) x = 30;
  else if (x === 12) x = 31;
  return x;
}

for (var i = 1; i < 12; i++) {
  sink = f(i);
}
pending…
Bitwise and Equality
function f(x) {
  return 28 | (x >> 3 ^ x) & 1 | (x !== 2) << 1;
}

for (var i = 1; i < 12; i++) {
  sink = f(i);
}
pending…
Lookup (Static Table)
function f(x) {
  return staticLookup[x];
}

for (var i = 1; i < 12; i++) {
  sink = f(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.

0 Comments