<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var obj = {
"tid": 1,
"cid": 0,
"uid": 0,
"mainPid": 0,
"postcount": 0,
"viewcount": 0,
"postercount": 0,
"deleted": 0,
"locked": 0,
"pinned": 0,
"timestamp": 0,
"upvotes": 0,
"downvotes": 0,
"lastposttime": 0,
"deleterUid": 0,
"timestampISO": "",
"lastposttimeISO": "",
"votes": 0,
"teaserPid": null
};
var c = _.clone(obj);
var c = Object.assign({}, obj);
var copy = {};
for (const k in obj) {
copy[k] = obj[k];
}
var copy = { obj };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash clone | |
object.assign | |
for | |
spread |
Test name | Executions per second |
---|---|
lodash clone | 473738.1 Ops/sec |
object.assign | 1383113.1 Ops/sec |
for | 352297.3 Ops/sec |
spread | 7071207.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explore what's being tested in this particular benchmark.
Benchmark Overview
The test case is designed to compare four different methods for creating a shallow copy of an object:
clone
functionObject.assign()
methodfor...in
loop{ ...obj }
)Library: Lodash
The benchmark uses the popular JavaScript utility library Lodash, which provides a wide range of functions for tasks such as string manipulation, array and object manipulation, and more.
In this specific test case, only one function from Lodash is used: clone
. The clone
function takes an object as input and returns a deep copy of it. However, in this benchmark, the clone
function is only used for shallow copying, which means it only copies the top-level properties of the original object without recursively cloning nested objects.
Options Compared
The four options are compared in terms of execution speed:
clone
function.Object.assign()
method to create a new object with the properties of the original object.{ ...obj }
) to create a shallow copy of the original object.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Device-Specific Considerations
The benchmark runs on a Windows 10 desktop device using Chrome 86. It's worth noting that the results may vary depending on the device platform, browser version, and JavaScript engine used.
Alternatives
If you're looking for alternative approaches to shallow copying objects in JavaScript, here are some options:
JSON.parse(JSON.stringify(obj))
: This method creates a deep copy of the original object but can be slower than other approaches due to the overhead of JSON parsing.Array.prototype.slice.call(obj)
: This method uses the slice()
method to create a shallow copy of the original object's properties.In summary, this benchmark provides valuable insights into the performance characteristics of different methods for creating shallow copies of objects in JavaScript. By understanding the pros and cons of each approach, developers can make informed decisions about which method to use depending on their specific requirements and performance needs.