<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var size = 5000000;
var MyObject = new Uint8Array(size);
for (let i = 0; i < size; ++i) {
MyObject[i] = Math.round(Math.random() * 255);
}
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = structuredClone(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Native structuredClone | |
JSON Parse |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 0.3 Ops/sec |
Native structuredClone | 205.7 Ops/sec |
JSON Parse | 0.2 Ops/sec |
Overview of the Benchmark
MeasureThat.net is used to compare the performance of different methods for cloning and copying JavaScript objects, specifically JSON arrays (Uint8Arrays). The benchmark is designed to test the execution speed of three approaches:
cloneDeep
methodstructuredClone
function (introduced in modern browsers)JSON.stringify
and JSON.parse
Options Comparison
Here's a brief overview of each approach, their pros and cons, and considerations:
cloneDeep
methodstructuredClone
functionJSON.stringify
and JSON.parse
Library Usage - Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for various tasks. In this benchmark, cloneDeep
is used to create a deep copy of the input object (MyObject
). The cloneDeep
function recursively clones all properties and sub-properties of the original object.
Special JS Feature - structuredClone
The structuredClone
function is a new feature introduced in modern browsers (Chrome 72+, Firefox 66+, Edge 83+) that allows creating exact copies of objects, including arrays and maps. It is designed to replace functions like JSON.parse(JSON.stringify())
for efficient cloning.
Benchmark Preparation Code
The script preparation code creates an array (MyObject
) with 5MB size, populates it with random values between 0 and 255, and then initializes a variable myCopy
to be cloned using each of the three methods.
Test Cases
Each test case uses one of the cloning methods:
cloneDeep
methodstructuredClone
functionJSON.stringify
and JSON.parse
Benchmark Results
The benchmark results show the execution speed (executions per second) for each test case on a Chrome 108 desktop environment. The native structuredClone
function appears to be the fastest, followed by JSON parsing, and then Lodash's cloneDeep
method.
Alternatives
Other alternatives for cloning JavaScript objects include:
However, these alternatives may incur additional overhead or have limitations (e.g., not supporting maps).
Keep in mind that this benchmark is specific to cloning JSON arrays and might not be representative for other use cases or objects. Always consider the specific requirements and constraints of your application when choosing a cloning method.