Skip to content

Instantly share code, notes, and snippets.

@liath
Created December 21, 2016 21:16
Show Gist options
  • Save liath/e83c9703647d1f8d1b27e84356ae1c93 to your computer and use it in GitHub Desktop.
Save liath/e83c9703647d1f8d1b27e84356ae1c93 to your computer and use it in GitHub Desktop.
JS Performance Test: for vs for..in vs Array.some
/* eslint max-len:0, no-console:0 */
const Benchmark = require('benchmark');
const id = require('uuid/v4');
const fileObject = {
filename: 'ApplesApplesApplesApplesApplesApples.txt',
};
const dupes = () => ([...Array(50000)].map((x) => ({
Filename: id(),
FileId: id(),
})));
const testFor = () => {
const duplicates = dupes();
duplicates[Math.floor(Math.random() * duplicates.length)].Filename = fileObject.filename;
const ret = fileObject;
const dupeCount = duplicates.length;
for (let i = 0; i < dupeCount; i += 1) {
if (duplicates[i].Filename.toUpperCase() === fileObject.filename.toUpperCase()) {
ret.isRevision = true;
ret.repositoryFileId = duplicates[i].FileId;
break;
}
}
return ret;
};
const testForIn = () => {
const duplicates = dupes();
duplicates[Math.floor(Math.random() * duplicates.length)].Filename = fileObject.filename;
const ret = fileObject;
for(const d in duplicates) {
if (duplicates[d].Filename.toUpperCase() === fileObject.filename.toUpperCase()) {
ret.isRevision = true;
ret.repositoryFileId = duplicates[d].FileId;
break;
}
}
return ret;
};
const testSome = () => {
const duplicates = dupes();
duplicates[Math.floor(Math.random() * duplicates.length)].Filename = fileObject.filename;
const ret = fileObject;
duplicates.some((dupe) => {
if (dupe.Filename.toUpperCase() === fileObject.filename.toUpperCase()) {
ret.isRevision = true;
ret.repositoryFileId = dupe.FileId;
return true;
}
return false;
});
return ret;
};
console.log('Tests running...');
const suite = new Benchmark.Suite();
suite
.add('for', testFor)
.add('for..in', testForIn)
.add('Array.some', testSome)
.on('cycle', (event) => {
console.log(String(event.target));
})
.on('complete', function complete() {
console.log(`Fastest is ${this.filter('fastest').map('name')}`);
})
.run({ async: true });
// console.log(test1());
// console.log(test2());
@liath
Copy link
Author

liath commented Dec 21, 2016

Surprisingly close results:

Tests running...
for x 3.98 ops/sec ±3.32% (14 runs sampled)
for..in x 3.63 ops/sec ±6.96% (14 runs sampled)
Array.some x 3.96 ops/sec ±3.14% (14 runs sampled)
Fastest is for

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment