optimizing if-else

Benchmark created by Truong Nguyen on


Test runner

Ready to run.

Testing in
TestOps/sec
stupid
var n = Math.floor((Math.random() * 8));
if (n === 1) console.log("1");
else if (n === 2) console.log("2");
else if (n === 3) console.log("3");
else if (n === 4) console.log("4");
else if (n === 5) console.log("5");
else if (n === 6) console.log("6");
else if (n === 7) console.log("7");
else if (n === 8) console.log("8");
else console.log("0");
ready
smart
var n = Math.floor((Math.random() * 8));

console.log("n: " + n);
if (n < 4) {
  if (n > 1) {
    if (n === 2) console.log("2");
    else console.log("3");
  } else {
    if (n === 1) console.log("1");
    else console.log("0");
  }
} else if (n > 4) {
  if (n > 6) {
    if (n === 8) console.log("8");
    else console.log("7");
  } else {
    if (n === 5) console.log("5");
    else console.log("6");
  }
} else console.log("4");
ready
switch case
var n = Math.floor((Math.random() * 8));
switch (n) {
  case 1:
    {
      console.log("1");
      break;
    }

  case 2:
    {
      console.log("2");
      break;
    }
  case 3:
    {
      console.log("3");
      break;
    }
  case 4:
    {
      console.log("4");
      break;
    }
  case 5:
    {
      console.log("5");
      break;
    }
  case 6:
    {
      console.log("6");
      break;
    }
  case 7:
    {
      console.log("7");
      break;
    }
  case 8:
    {
      console.log("8");
      break;
    }
  default:
    console.log("0");
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Truong Nguyen on