JSON.parse(JSON.stringify()) vs. cloneDeep vs. custom clone

Benchmark created on


Preparation HTML

<script type="module">
const {cloneDeep} = await import ("https://cdn.jsdelivr.net/npm/lodash-es@4.17.21/lodash.min.js");

window.cloneDeep = cloneDeep;
</script>

Setup

const MyObject = {
  description: 'Creates a deep copy of source, which should be an object or an array.',
  myNumber: 123456789,
  myBoolean: true,
  jayson: {
    stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
    parse: 'JSON.parse() method parses a JSON string...'
  }
};

function objectUtilsClone(obj) {
    let clone

    if (typeof obj !== 'object') {
      return obj
    }
    if (!obj) {
      return obj
    }
    if (Array.isArray(obj)) {
      clone = []
      for (let i = 0; i < obj.length; i += 1) {
        clone[i] = objectUtilsClone(obj[i])
      }
      return clone
    }

    clone = {}
    Object.keys(obj).forEach((key) => {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        clone[key] = objectUtilsClone(obj[key])
      }
    })

    return clone
}

Test runner

Ready to run.

Testing in
TestOps/sec
JSON.parse(JSON.stringify(MyObject));
JSON.parse(JSON.stringify(MyObject));
ready
cloneDeep(MyObject);
cloneDeep(MyObject);
ready
objectUtilsClone(MyObject);
objectUtilsClone(MyObject);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.