<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var obj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
var obj2 = JSON.parse(JSON.stringify(obj));
var obj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
var obj2 = _.clone(obj, true);
var obj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
var obj2 = Object.assign({}, obj);
var obj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
var obj2 = R.clone(obj);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
json stringify | |
lodash deep clone | |
Object.assign | |
Ramda clone |
Test name | Executions per second |
---|---|
json stringify | 290723.2 Ops/sec |
lodash deep clone | 919370.3 Ops/sec |
Object.assign | 2818468.8 Ops/sec |
Ramda clone | 419057.2 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark definition is a set of instructions that outlines how to prepare for the test. In this case, it defines an object obj
with various properties (e.g., strings, numbers, arrays) and another object anotherObj
. The goal is to create a deep clone of obj
.
Options Compared
Four different approaches are being tested:
JSON.stringify()
and then parsing it back into an object using JSON.parse()
._.clone()
function from Lodash, which is a popular utility library for functional programming in JavaScript.Object.assign()
method to create a new object by copying the properties of the original object into it.R.clone()
function from Ramda, another popular utility library for functional programming in JavaScript.Pros and Cons of Each Approach
_.cloneDeep()
, not just _
.)Object.assign()
directly on the object, not creating a new object.)Library Descriptions
Special JS Features/Syntax
There are no special JS features or syntax used in this benchmark, aside from the external libraries mentioned above.
Other Alternatives
For creating deep clones, other alternatives to the ones mentioned above include:
Array.prototype.slice()
to create a new array and then uses Object.assign()
to copy properties from the original object.Keep in mind that these alternatives may have different trade-offs in terms of performance, memory usage, or compatibility with older browsers.