Created
December 21, 2016 21:16
-
-
Save liath/e83c9703647d1f8d1b27e84356ae1c93 to your computer and use it in GitHub Desktop.
JS Performance Test: for vs for..in vs Array.some
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Surprisingly close results: