Skip to content

Instantly share code, notes, and snippets.

@jalal246
Last active October 11, 2019 14:42
Show Gist options
  • Select an option

  • Save jalal246/16e645828b411347d71590d4cff5867f to your computer and use it in GitHub Desktop.

Select an option

Save jalal246/16e645828b411347d71590d4cff5867f to your computer and use it in GitHub Desktop.
JavaScript Performance Test: conditional object VS regular if/else

Motivation

I've worked on function that requires a heavy usage of if/else statement. I came up with an idea. Object with keys return the result.

const condition = {
  up: x1 > x2 && y1 > y2,
  down: x1 < x2 && y1 < y2
};

// or?
if (isUp) {
  return x1 > x2 && y1 > y2;
}
return x1 < x2 && y1 < y2;

Is using this conditional object is better than regular conditions? Some think this is crazy but bear with me, I was curious about the results.

Conclusion

  • object with Condition took: 23.00499999546446 ms
  • regular Condition took: 14.974999998230487 ms

For now, going to stick with conventional usage of regular condition statement.

/**
* Utility, generates random number.
*/
function randNumber() {
return Math.ceil(Math.random() * 10);
}
/**
* Utility, generates random boolean value.
*/
function randBoolean() {
return Math.random() >= 0.5;
}
/**
* Gets condition result with object.
*/
function test1(direction, x1, x2, y1, y2) {
const condition = {
up: x1 > x2 && y1 > y2,
down: x1 < x2 && y1 < y2
// zero: x1 < x2 || y1 < y2
};
return condition[direction];
}
/**
* Gets condition result regular if statement.
*/
function test2(isUp, x1, x2, y1, y2) {
if (isUp) {
return x1 > x2 && y1 > y2;
}
return x1 < x2 && y1 < y2;
// if (isDown) {
// }
// return x1 < x2 || y1 < y2;
}
function runTest() {
let perf;
perf = performance.now();
for (let i = 0; i < 10000; i++) {
const x1 = randNumber();
const x2 = randNumber();
const y1 = randNumber();
const y2 = randNumber();
test1(randBoolean() ? "up" : "down", x1, x2, y1, y2);
}
console.log(`object with Condition took: ${performance.now() - perf} ms`);
perf = performance.now();
for (let i = 0; i < 10000; i++) {
const x1 = randNumber();
const x2 = randNumber();
const y1 = randNumber();
const y2 = randNumber();
test2(randBoolean(), x1, x2, y1, y2);
}
console.log(`regular Condition took: ${performance.now() - perf} ms`);
}
runTest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment