Run details:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
Chrome 105
Mac OS X 10.15.7
Desktop
2 years ago
Test name Executions per second
Object.fromEntries 2252.3 Ops/sec
Reduce (reuse object) 11298.3 Ops/sec
Reduce (creating temporary objects) 113.5 Ops/sec
Map 1913.4 Ops/sec
forEach 11441.5 Ops/sec
for of 12784.1 Ops/sec
for i 1182.4 Ops/sec
for i saved length variable 2181.9 Ops/sec
Script Preparation code:
AخA
 
var data = Array.from(Array(10000).keys()).map(i => ({id: i, value: `val_${i}`}));
Tests:
  • Object.fromEntries

     
    Object.fromEntries(data.map(obj => [obj.id, obj]));
  • Reduce (reuse object)

     
    data.reduce((acc, obj) => {
      acc[obj.id] = obj;
      return acc;
    }, {});
  • Reduce (creating temporary objects)

     
    data.reduce((acc, obj) => ({
      ...acc,
      [obj.id]: obj
    }), {});
  • Map

     
    new Map(data.map(obj => [obj.id, obj]));
  • forEach

     
    const res = {};
    data.forEach(obj => {
        res[obj.id] = obj; 
    });  
  • for of

     
    const res = {};
    for (const obj of data) {
        res[obj.id] = obj; 
    }  
  • for i

     
    const res = {};
    for (let i = 0; i < data.length; i++) {
        const obj = data[i];
        res[obj.id] = obj; 
    }  
  • for i saved length variable

     
    const res = {};
    const length = data.length;
    for (let i = 0; i < length; i++) {
        const obj = data[i];
        res[obj.id] = obj; 
    }