深拷贝性能测试

67 阅读1分钟

使用一个13000的数组测试了4种深拷贝,计算了耗时,先说结果: 耗时从大到小:

  1. lodash的cloneDeep,耗时20ms
  2. structuredClone,耗时15ms
  3. JSON.parse(JSON.stringify()),耗时8ms
  4. 自己写,耗时5ms

所以如果是大数据,推荐大家自己封装一个深拷贝的公用方法,可以提高一些性能

1、JSON.parse(JSON.stringify()):

import { useLastChanged } from '@vueuse/core'; // 最近在学vueuse,就用这个api练练手

const orginData = [...] // 13000条数据
const newData = ref()
const lastChanged = useLastChanged(newData) // counter每次变化后都会更新

// 8ms
const deepClone = () => {
    console.log(new Date().getTime())
    newData.value = JSON.parse(JSON.stringify(orginData))
    console.log(newData.value, lastChanged)
}

2、structuredClone:这个是浏览器提供的原生api,只对基础数据类型管用,如果数据是Proxy就不能用了

 15ms
 const deepClone = () => {
      console.log(new Date().getTime())
      newData.value = structuredClone(orginData)
      console.log(newData.value, lastChanged)
  }

3、lodash的deepClone

 import _cloneDeep from 'lodash-es/cloneDeep';

// 20ms
 const deepClone = () => {
      console.log(new Date().getTime())
      newData.value = _cloneDeep(orginData)
      console.log(newData.value, lastChanged)
  }

4、自己写 deepClone.ts

export const deepCopyFn = (obj: any) =>{
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }

  let copy: any;

  if (obj instanceof Date) {
    copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }

  if (Array.isArray(obj)) {
    copy = [];
    for (let i = 0; i < obj.length; i++) {
      copy[i] = deepCopyFn(obj[i]);
    }
    return copy;
  }

  if (typeof obj === 'object') {
    copy = {};
    for (let key in obj) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(key)) {
        copy[key] = deepCopyFn(obj[key]);
      }
    }
    return copy;
  }
}

使用:

 // 5ms
 const deepClone = () => {
      console.log(new Date().getTime())
      newData.value = deepCopyFn(orginData)
      console.log(newData.value, lastChanged)
  }