Cloning Objects (v5)

Revision 5 of this benchmark created on


Description

How to clone object comparison

Preparation HTML

<script src="https://cdn.jsdelivr.net/npm/lodash-es@4.17.21/lodash.min.js"></script>

Setup

const person = {
  name: 'John Doe',
  age: 34,
  address: {
    country: 'USA',
    city: 'Boston',
  },
  hobbies: ['Reading', 'Cooking'],
  active: true,
  signDate: new Date(),
  superPowers: new Set(['strength', 'fly']),
  knwoledge: new Map([['history', 'good'], ['math', 'bad']]),
};

const lodash_CloneDeep = _.cloneDeep;

function spreadClone(value){
	if (value == null){
		return value;
	}
	const typeStr = typeof value;
	if (typeStr == "function"){
		return (...args) => value(...args);
	}
	if (typeStr == "object"){
		value = {...value};
		const keys = Object.keys(value);
		for (const k of keys){
			value[k] = spreadClone(value[k]);
		}
	}
	return value;
}
function assignClone(value){
	if (value == null){
		return value;
	}
	const typeStr = typeof value;
	if (typeStr == "function"){
		return (...args) => value(...args);
	}
	if (typeStr == "object"){
		value = Object.assign({}, {...value});
		const keys = Object.keys(value);
		for (const k of keys){
			value[k] = assignClone(value[k]);
		}
	}
	return value;
}

Test runner

Ready to run.

Testing in
TestOps/sec
spreadClone
let spreadCopy;
for (let i = 0; i < 100000; i++) {
  spreadCopy= spreadClone(person);
}
ready
structuredClone
let structure;
for (let i = 0; i < 100000; i++) {
  structure = structuredClone(person);
}
ready
stringify + parse
let deepCopy;
for (let i = 0; i < 100000; i++) {
  deepCopy = JSON.parse(JSON.stringify(person));
}
ready
lodash
let lodashCopy;
for (let i = 0; i < 100000; i++) {
  lodashCopy = lodash_CloneDeep(person);
}
ready
Object.assign
let assignCopy;
for (let i = 0; i < 100000; i++) {
  assignCopy = assignClone(person);
}
ready

Revisions

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