Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Deep copy algo vs JSON manipulation - 6k lines of prices
(version: 0)
Comparing performance of:
JSON copy vs Deep copy
Created:
one year ago
by:
Guest
Jump to the latest result
Script Preparation code:
function deepCopy(obj) { var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = deepCopy(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = deepCopy(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }; function generate_data() { let data = { 'prices': [], 'my object': [ {'object a': 'object object'}, {'object b': 'object object'}, {'object c': 'object object', 'objectd': 36}, 5 ] }; // Helper function to generate random product names function generateProductName() { const products = ['Laptop', 'Phone', 'Tablet', 'Headphone', 'Speaker', 'Monitor', 'Keyboard', 'Mouse', 'Smartwatch', 'Camera']; const adjectives = ['Super', 'Ultra', 'Pro', 'Max', 'Plus', 'Lite', 'Mini', 'Advanced', 'Portable', 'Wireless']; const randomProduct = products[Math.floor(Math.random() * products.length)]; const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)]; return `${randomAdjective} ${randomProduct}`; } // Helper function to generate random prices function generatePrice() { return (Math.random() * 1000).toFixed(2); // Random price between 0 and 1000 with 2 decimal places } // Generate 6000 product name and price entries for (let i = 0; i < 6000; i++) { const product = generateProductName(); const price = generatePrice(); data['prices'].push({ 'product': product, 'price': parseFloat(price) }); } return data; }; var data = generate_data();
Tests:
JSON copy
a = JSON.parse(JSON.stringify(data));
Deep copy
a = deepCopy(data);
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
JSON copy
Deep copy
Fastest:
N/A
Slowest:
N/A
Latest run results:
Run details:
(Test run date:
one year ago
)
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36
Browser/OS:
Chrome 130 on Mac OS X 10.15.7
View result in a separate tab
Embed
Embed Benchmark Result
Test name
Executions per second
JSON copy
817.4 Ops/sec
Deep copy
3391.6 Ops/sec
Autogenerated LLM Summary
(model
gpt-4o-mini
, generated one year ago):
The benchmark provided compares two different methods for creating a deep copy of an object in JavaScript: **JSON manipulation** and a **custom deep copy function**. ### Test Cases Explained 1. **JSON Copy** - **Method**: `a = JSON.parse(JSON.stringify(data));` - **Description**: This method leverages JSON serialization and deserialization to create a deep copy of the data. The object is first converted to a JSON string using `JSON.stringify()`, and then back to an object with `JSON.parse()`. - **Pros**: - Simple and concise implementation. - Works well for basic objects without methods, special objects, or circular references. - **Cons**: - It cannot handle functions, undefined, or non-serializable values (like `Date`, `RegExp`, etc.), which may lead to data loss or unexpected results. - Any prototype methods or properties from the original object are lost in the resulting object. 2. **Deep Copy** - **Method**: `a = deepCopy(data);` - **Description**: This method uses a custom recursive function to create a deep copy of the object. It explicitly checks for several JavaScript types (like Date and Array) and creates clones accordingly. - **Pros**: - More versatile and robust, as it can handle a variety of data types, including arrays, objects, and dates. - Recursively checks properties, maintaining object references and preserving prototypes. - **Cons**: - More complex and potentially slower for very large or deeply nested objects due to recursion. - May not handle circular references, which can lead to stack overflow errors unless specifically programmed to do so. ### Other Considerations - **Performance**: In the benchmark results, the **JSON copy** method is faster with approximately 795 executions per second, compared to 562 executions per second for the **deep copy** method. This is attributed to the inherent efficiency of native methods in JavaScript engines. - **Data Validation**: Ensure that the depth and structure of the object being copied do not exceed limits defined by JavaScript's call stack size, especially for recursive functions like `deepCopy`. ### Other Alternatives - **Lodash's `cloneDeep` method**: This utility library provides a `cloneDeep` method designed to handle a wide variety of JavaScript types and structures, including arrays, objects, dates, and circular references. It is a good alternative if you need a reliable deep copy solution without implementing your own. - **Structured Cloning**: For environments that support it (like modern browsers with `structuredClone()`), this built-in method can create a deep copy of almost any JavaScript value, including DOM elements, though it also has limitations in terms of what it can clone. ### Summary Choosing between **JSON manipulation** and **custom deep copy** hinges on the specific needs of the application in question, such as the types of data being manipulated and performance requirements. For simple structures, JSON methods may suffice, while complex, nested, or varied structures may benefit from a more tailored approach like `deepCopy` or using libraries like Lodash.
Related benchmarks:
Closure v Prototypical Objects 3
object cope speed test
Deep Clone vs JSON.Stringify
DeepFreeze vs Lodash cloneDeep vs JSON Clone
Deep Clone vs JSON.Stringify vs structuredClone
Deep copy algo vs JSON manipulation
Deep copy algo vs JSON manipulation - 120k lines of prices
Comments
Confirm delete:
Do you really want to delete benchmark?