I implemented both approaches as two methods with the same signature (forBreakMethod(x)
and findMethod (x)
) and passed them through a simple performance test spec.
(() => {
const test = (DATA_LENGTH = 1000, INDEX = 9, TESTS_COUNT = 10000) => {
// data initialization
const employees = [];
for (let i = 1; i <= DATA_LENGTH; i++){
employees.push({ id: i });
}
// methods initialization
const forBreakMethod = (x) => {
const length = employees.length;
for (let i = 0; i < length; i++) {
if (x === employees.id) {
return employees[i];
}
}
}
const findMethod = (x) => {
return employees.find(item => x === item.id);
}
// for-break test
const time1 = performance.now();
for (let i = 0; i < TESTS_COUNT; i++) {
forBreakMethod(INDEX);
}
const time2 = performance.now();
console.log(`[for-break] find ${INDEX} from ${DATA_LENGTH}: ${time2 - time1}`);
// find test
const time3 = performance.now();
for (let i = 0; i < TESTS_COUNT; i++) {
findMethod(INDEX);
}
const time4 = performance.now();
console.log(`[Array.find] find ${INDEX} from ${DATA_LENGTH}: ${time4 - time3}`);
console.log('---------------');
};
test(10, 1, 1000000);
test(10, 5, 1000000);
test(10, 9, 1000000);
console.log('\n');
test(100, 10, 100000);
test(100, 50, 100000);
test(100, 99, 100000);
console.log('\n');
test(1000, 10, 10000);
test(1000, 500, 10000);
test(1000, 999, 10000);
console.log('\n');
test(10000, 10, 10000);
test(10000, 5000, 10000);
test(10000, 9999, 10000);
})();
A conclusion I see is that the Array.find approach has an advantage if the item we want to find lives in the left part of the data array, but its performance getting low when the result index goes to the right. The for-break approach seems more stable, since its performance does not depend on the index we want to find, but its cost is significant.
So very rough, I would say that the Array.find approach could be considered as more performant if we are going to walk through the first half of the data array, otherwise I would use the for-break approach.
PS Chrome, Safari, Firefox, 2018.