Skip to content

Instantly share code, notes, and snippets.

@akx
Created March 15, 2018 09:02
Show Gist options
  • Save akx/20e759d3441100e1e60700455473867b to your computer and use it in GitHub Desktop.
Save akx/20e759d3441100e1e60700455473867b to your computer and use it in GitHub Desktop.
for loops vs. every
$ node index.js
for: 1196073 hz
every: 417669 hz
Fastest is for
$
// yarn add benchmark lodash
// yarn index.js
const isEqual = require('lodash/isEqual');
const assert = require('assert');
const Benchmark = require('benchmark');
function compareKeySubsetForLoop(objects, keys, comparator = isEqual) {
if (objects.length <= 1) return true;
if (keys.length === 0) return true;
for (let keyIndex = 0; keyIndex < keys.length; keyIndex += 1) {
const key = keys[keyIndex];
const cmpVal = objects[0][key];
for (let objIndex = 1; objIndex < objects.length; objIndex += 1) {
if (!comparator(objects[objIndex][key], cmpVal)) {
// Early-out at the first mismatch.
return false;
}
}
}
return true;
}
function compareKeySubsetEvery(objects, keys, comparator = isEqual) {
if (objects.length <= 1) return true;
if (keys.length === 0) return true;
return keys.every((key) => {
const cmpVal = objects[0][key];
return objects.every(obj => comparator(obj[key], cmpVal));
});
}
const manyObjects = [
{a: 1, b: 2},
{a: 1, b: 2, c: 4},
{a: 1, b: 2, c: 4, d: 5},
{a: 1, b: 2},
{a: 1, b: 2, c: 4},
{a: 1, b: 2, c: 4, d: 5},
{a: 1, b: 2},
{a: 1, b: 2, c: 4},
{a: 1, b: 2, c: 4, d: 5},
];
const twoObjects = [
{a: 1, b: 2},
{a: 1, b: 3},
];
const noCommonAObjects = [
{a: 1, b: 2},
{a: 1, b: 3},
{a: 2, b: 3},
];
function testFunc(compareKeySubset) {
assert(compareKeySubset(twoObjects, ['a']));
assert(!compareKeySubset(twoObjects, ['b']));
assert(compareKeySubset(manyObjects, ['a']));
assert(compareKeySubset(manyObjects, ['a', 'b']));
assert(!compareKeySubset(noCommonAObjects, ['a']));
assert(compareKeySubset([], ['a']));
assert(compareKeySubset(twoObjects, []));
}
var suite = new Benchmark.Suite;
suite.add('for', () => testFunc(compareKeySubsetForLoop));
suite.add('every', () => testFunc(compareKeySubsetEvery));
suite.on('cycle', (event) => console.log(`${event.target.name}: ${Math.round(event.target.hz)} hz`));
suite.on('complete', () => console.log('Fastest is ' + suite.filter('fastest').map('name')));
suite.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment