컴퓨터 공학/JavaScript

Node.js 객체 복사 방식에 따른 수행시간 간단 비교

혼새미로 2022. 1. 12. 22:21
반응형

"Before and After Makeup Photo of Albert Einstein sticking his tongue out, in a photorealistic style" from DALL-E 2

개요

JS에서 각 객체의 깊은 복사 방식에 따른 수행시간을 간단하게 비교한다.

원본 객체

const obj1 = {
    a: 1,
    b: "string",
    c: {
        name: "Leon",
        age: "29"
    }
};

 

JSON 복사

function jsonCopy(obj){
    return JSON.parse(JSON.stringify(obj));
}

Lodash 복사

function lodashCopy(obj){
    return lodash.cloneDeep(obj);
}

재귀함수 복사

/** 객체 깊은 복사 */
function cloneObjectDeep(obj) {
    const clone = {};
    if (typeof obj !== 'object') return obj;
    for (const key in obj) {
        const value = obj[key];
        if (Array.isArray(value)) {
            clone[key] = cloneArrayDeep(value);
        } else if (value instanceof Date) {
            clone[key] = value;
        } else if (typeof value === 'object' && value != null) {
            clone[key] = cloneObjectDeep(value);
        } else {
            clone[key] = value;
        }
    }
    return clone;
}

/** 배열 깊은 복사 */
function cloneArrayDeep(arr) {
    const clone = [];
    if (Array.isArray(arr) === false) return clone;
    for (const item of arr) {
        if (Array.isArray(item)) {
            clone.push(cloneArrayDeep(item));
        } else if (item instanceof Date) {
            clone.push(item);
        } else if (typeof item === 'object' && item != null) {
            clone.push(cloneObjectDeep(item));
        } else {
            clone.push(item);
        }
    }
    return clone;
}

테스트 결과

결론

  • JSON 복사 방식이 가장 느리다.
  • 재귀함수 방식이 JSON 방식보다 약 15배 빠르다.
  • 재귀함수 방식으로 객체를 복사하자.

참고자료

JSBEN.CH Performance Benchmarking Playground for JavaScript

rapid-clone - npm (npmjs.com)

반응형