When you wants to working with collections of data, there is a conclusion between Object and Array. Sometimes Array works great and sometime Object works outstanding. We are going to testing these 2 things when million of data comes into an empty Array & Object, and how they perform. How many times they needs to update data.
Update operation speed comparisons.
Array updating speed with 5M. data
// Array.. const arr = []; for (let i = 0; i < 5000000; i++){ arr.push({ id: I, value: `${i * 84}` }); } // Updating data.. console.time('ARRAY SPEED'); let id = 4999998; const findItem = arr.find(item => item.id === id); findItem.value = 'HACKED BY ASAD ANIK'; console.timeEnd('ARRAY SPEED');
ARRAY SPEED: 48.817ms
Object updating speed with 5M. data
// Object.. const obj = {}; for (let i = 0; i < 5000000; i++){ obj[i] = { id: I, value: `${i * 84}` }; } // Updating data.. console.time('OBJECT SPEED'); let id = 4999998; obj[id].value = 'HACKED BY RAKHIYAATUL KUBRA'; console.timeEnd('OBJECT SPEED');
OBJECT SPEED: 0.085ms
Delete operation speed comparisons.
Array’s Deleting speed.
// Array.. const arr = []; for (let i = 0; i < 5000000; i++){ arr.push({ id: I, value: `${i * 84 + 77}` }); } // Deleting data.. console.time('ARRAY DELETE SPEED'); let id = 4999999; const index = arr.findIndex(item => item.id === id); arr.splice(index, 1); console.timeEnd('ARRAY DELETE SPEED');
ARRAY DELETE SPEED: 49.457ms
Object’s Deleting speed.
// Object.. const obj = {}; for (let i = 0; i < 5000000; i++){ obj[i] = { id: i, value: `${i * 84 + 77}` }; } // Deleting data.. console.time('OBJECT DELETE SPEED'); let id = 4999999; delete obj[id]; console.timeEnd('OBJECT DELETE SPEED');
OBJECT DELETE SPEED: 0.084ms
Reduce Vs Map, Filter method.
Reduce is more powerful method than Map and Filter. Let’s see the prove.
→ Map, Filter
const arr = []; for (let i = 0; i < 5000000; i++){ arr.push(i); } // Not Optimised operation.. console.time('MAP_FILTER'); arr.filter(item => item %2 === 0).map(item => item * 2); console.timeEnd('MAP_FILTER');
MAP_FILTER: 153.749ms
→ Reduce
const arr = []; for (let i = 0; i < 5000000; i++){ arr.push(i); } // Optimised operation.. console.time('REDUCE_WAY'); arr.reduce((acc, cur) => { if (cur %2 === 0){ acc.push(cur * 2); } return acc; }, []); console.timeEnd('REDUCE_WAY');
REDUCE_WAY: 89.065ms
Decision making
→ When is time to build an Application, so we have to decide about its task. Is your Application are handling lots of traversing ? ⇒ So go for working with Array Operations in the most case. it’s totally fine.
→ And if your Application handles lot’s of CRUD operations like Create, Retrieve, Read, Update, Delete ? ⇒ So go for working with Object Operations in the most case. It’s fine.
Top comments (0)