var obj = {}
for (let i = 0; i < 1000; i++) {
obj[`test_${i}`] = `value_${i}`;
}
const newObject = Object.keys(obj).reduce((object, key) => {
if (key) {
object[key] = obj[key]
}
return object
}, {})
const newObject = { obj };
Object.keys(newObject).forEach(key => {
delete newObject[key];
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
create new object | |
directly delete |
Test name | Executions per second |
---|---|
create new object | 5963.0 Ops/sec |
directly delete | 7104.5 Ops/sec |
I'd be happy to explain the benchmark and its various components.
Benchmark Overview
The benchmark, named "delete property of object vs create new object", measures the performance difference between two approaches: creating a new object by copying an existing one and directly deleting properties from the original object. This benchmark tests the efficiency of these approaches in JavaScript.
Options Compared
There are two options being compared:
{ ...obj }
) or Object.keys()
and reduce()
. The idea is to create a shallow copy of the original object, which allows for the direct deletion of properties.delete
keyword.Pros and Cons
Pros:
Cons:
Pros:
Cons:
Library Usage
None of the benchmark cases explicitly uses any external libraries.
Special JS Features/Syntax
Neither of the two approaches requires special JavaScript features or syntax. The benchmark focuses on general JavaScript concepts, making it accessible to a wide range of developers.
Other Alternatives
Other alternatives for creating new objects or deleting properties from an object include:
Object.assign()
to create a shallow copycloneDeep()
function to create deep copiesfor...in
loopsKeep in mind that the performance difference between these approaches may vary depending on the specific use case, JavaScript engine, and system configuration.
In summary, this benchmark provides a straightforward comparison of two common approaches to creating new objects and deleting properties from an object in JavaScript. The results can help developers optimize their code for better performance and resource usage in various scenarios.