Test name | Executions per second |
---|---|
Find | 10.4 Ops/sec |
For loop | 5.3 Ops/sec |
Object | 973.6 Ops/sec |
Map | 245.9 Ops/sec |
var arr = [];
for (let i = 0; i < 10000; i++) {
arr.push({id: i, name: `object${i}`});
}
for (let i = 0; i < 10000; i+=2) {
const val = arr.find(x => x.id === i);
if (val.name !== `object${i}`) {
throw new Error('wrong found');
}
}
for (let i = 0; i < 10000; i+=2) {
for (let j = 0, len = arr.length; j < len; j++) {
if (arr[j].id === i) {
const val = arr[j];
if (val.name !== `object${i}`) {
throw new Error('wrong found');
}
break;
}
}
}
const obj = arr.reduce((acc, x) => {acc[x.id] = x; return acc;}, {});
for (let i = 0; i < 10000; i+=2) {
const val = obj[i];
if (val.name !== `object${i}`) {
throw new Error('wrong found');
}
}
const mapping = new Map(arr.map(x => [x.id, x]));
for (let i = 0; i < 10000; i+=2) {
const val = mapping.get(i);
if (val.name !== `object${i}`) {
throw new Error('wrong found');
}
}