eval vs obj

Benchmark created on


Setup

const compare = {
  equal: (a, b) => a === b,
  greaterThan: (a, b) => a > b,
  smallerThan: (a, b) => a < b,
  greaterOrEqual: (a, b) => a >= b,
  smallerOrEqual: (a, b) => a <= b,
  notEqual: (a, b) => a !== b
}

const compareStr = {
  equal: "===",
  notEqual: "!==",
  greaterThan: ">",
  greaterThanOrEqual: ">=",
  lessThan: "<",
  lessThanOrEqual: "<="
};


const N = 1000;
const numOperators = Object.keys(compare).length;
const currentValues = new Array(N).fill(0).map(() => Math.random());
const targetValues = new Array(N).fill(0).map(() => Math.random());



const evaluatorsEval = new Array(numOperators).fill(0).map((op, i) => { 
    const opStrings = Object.values(compareStr);

    const firstOp = opStrings[i];
    const secondOp = opStrings[(i+1) % numOperators];
    const thirdOp = opStrings[(i+2) % numOperators];

    const evalAll = Math.random() < 0.5;
    const fnString = evalAll 
        ? `(current, target) => (current ${firstOp} target) && (current ${secondOp} target) && (current ${thirdOp} target);` 
        : `(current, target) => (current ${firstOp} target) || (current ${secondOp} target) || (current ${thirdOp} target)`;
    
    const fn = eval(fnString)
    return fn;
});



const evaluatorsObj = new Array(numOperators).fill(0).map((_, i) => {
    const ops = Object.values(compare);
    const firstIdx = i;
    const secondIdx = (i + 1) % numOperators;
    const thirdIdx = (i + 2) % numOperators;
    

    const first = (current, target) => {
        return ops[firstIdx](current, target)
    };

    const second = (current, target) => {
        return ops[secondIdx](current, target)
    };

    const third = (current, target) => {
        return ops[thirdIdx](current, target)
    };

    const evalAll = Math.random() < 0.5;

    const arr = [first, second, third];

    if (evalAll) {
    	return (current, target) => {
    		 for (let fn of arr) {
                if (!fn(current, target)) {
                    return false;
                }
            }
            return true;	
    	}
    }
    
	return (current, target) => {
      for (let fn of arr) {
      	if (fn(current, target)) {
      		return true;
        }
      }    
    }   
});


Test runner

Ready to run.

Testing in
TestOps/sec
eval
const results = [];

for (let i = 0; i < N; i++) {
	results.push(evaluatorsEval[i % numOperators](currentValues[i], targetValues[i]));
}
ready
object
const results = [];

for (let i = 0; i < N; i++) {
	results.push(evaluatorsObj[i % numOperators](currentValues[i], targetValues[i]));
}
ready

Revisions

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