var input = [];
for (var i = 0; i < 50000; i++) {
input.push({
id: i,
data: 'something'
})
}
const index = input.findIndex(val => val.id === 999);
input.splice(index, 1, {id: 999, data: 'somethingElse'});
const index = input.findIndex(val => val.id === 999);
input[index] = {id: 999, data: 'somethingElse'}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array splice | |
Object property assign |
Test name | Executions per second |
---|---|
Array splice | 1242518.0 Ops/sec |
Object property assign | 1250126.5 Ops/sec |
The benchmark named "Array splice vs array assign" compares two methods of updating an object within an array in JavaScript: using the splice
method and using direct assignment of an object property.
Array splice:
const index = input.findIndex(val => val.id === 999);
input.splice(index, 1, {id: 999, data: 'somethingElse'});
id
999 using findIndex
. It then removes that object and inserts a new object at the same index using splice
.splice
can directly modify the original array and is useful for operations where you need to both remove and add an element simultaneously.Object property assign:
const index = input.findIndex(val => val.id === 999);
input[index] = {id: 999, data: 'somethingElse'};
id
999, but it replaces the object at that index directly with a new object.splice
for simply replacing an object, as it only requires accessing the index and changing the value.splice
, the underlying implementation might create intermediate arrays or deal with re-allocation, which can be less memory efficient. Direct assignment only replaces a reference, leading to a smaller memory overhead.Using map
: If bulk updates across an array are needed, using map
can be a more functional approach:
input = input.map(val => val.id === 999 ? {id: 999, data: 'somethingElse'} : val);
Using Libraries: Libraries like lodash or Immutable.js can manage state updates more efficiently. For instance, Immutable.js helps in maintaining immutability which leads to reliable performance in larger applications.
In summary, the benchmark evaluates two different approaches to updating an array of objects, with performance metrics clearly favoring direct assignment over splice. Each method has its use cases and can be chosen based on specific requirements at hand.