前端: 有你不知道的优化的点(性能/代码质量)

501 阅读3分钟

这是我参与8月更文挑战的第1天,活动详情查看:8月更文挑战

代码优化可以让你的性能更好运行流畅,或者说可以让你的代码更简短,更具备维护性

优化点(性能)1

  • 如下面代码 arr1 / arr2 俩个数组之间找相同的数据(id相同即为相同)
  • 不好的方法就是 如下面equalArr1的结果做
  • equalArr1:也能求出来相同的数据(两成循环嵌套)
  • find方法也是隐式循环 具体可以参考文章:自己实现一个find的方法

不好的实现方案

 const arr1 = [{name: '张三', id: 1}, {name: '李四', id: 2}, {name: '王五', id: 3}, {name: '赵四', id: 4}];
 const arr2 = [{name: '张三', id: 1}, {name: '李四', id: 2}, {name: '王五', id: 3}];
 
 const equalArr1 = arr1.filter(item => {
       const findItem = arr2.find(child => child.id === item.id);
       if(findItem) {
          return item
      }
  })
console.log(equalArr1,'equalArr1')
//输出:[{name: '张三', id: 1}, {name: '李四', id: 2}, {name: '王五', id: 3}]

好的实现方案

  • 实现一个map对象
  • 只需要循环一次set Map对象下
  • get获取map对象 有的话返回该对象,没有的话返回undefined
  • 优化的点 减少循环(可能我定义的数据比较少,要是数据比较大的话就能明显对比出来了)
const arr1 = [{name: '张三', id: 1}, {name: '李四', id: 2}, {name: '王五', id: 3}, {name: '赵四', id: 4}];
 const arr2 = [{name: '张三', id: 1}, {name: '李四', id: 2}, {name: '王五', id: 3}];
 
let arrMap = new Map();
arr2.forEach(item => arrMap.set(item.id, item));

const equalArr2 = arr1.filter(item => {
      if(arrMap.get(item.id)) {
          return item
      }
 })

优化点2(性能)

  • 咱们再实现charts图表的时候多图例的时候
  • 或者说咱们可是实现一个图表可配置(BI)场景
  • 咱们可能都会首选echarts 毕竟都出来好多年了也一直再维护 问题就是echarts不会自动销毁实例,就在你的内存中占用,当达到一定的时候就会给你的造成内存泄漏,界面崩溃的问题

优化点就是 以vue为例 就是必须要在咱们beforeDestroy 的生命周期里面把实例销毁 代码如下 可以用mixins 引入对多个界面混入

export const chartsDestroy = {
  beforeDestroy() {
    try {
      if (this.myChart) {
        this.myChart.getZr().off('click');
        this.myChart.off('click');
        this.myChart.off('mouseover');
        this.myChart.off('mouseout');
        this.myChart.clear();
        this.myChart.dispose();
        this.myChart = null;
        console.log('charts destroy');
      }
          
    } catch (error) {
      console.log(error, 'charts error');
    }
    
  }
}; 

优化点3(质量)

不好的判断方法

if(type === 'Z1' || type === 'Z2' || type === 'Z3' || type === 'Z4') {
 console.log('>>>>>>>>>>>>>>>>>>.....................')
}

好的方案

const container = ['Z1','Z2','Z3', 'Z4'];
if(container.includes(type)) {
 console.log('>>>>>>>>>>>>>...................')
}

优化点3(质量)

不好的方案

if(type === 'a') {
  fn1()
}else if(type === 'b') {
  fn2()
}else if(type === 'c') {
  fn3()
}

好的方案

const container = {
 a: fn1,
 b: fn2,
 c: fn3
}

//直接
container[type]()

优化点4(质量)

不好的方案

let a;
if(type) {
 a = 1;
} else {
 a = 2
}

好的方案

const a = type ? 1 : 2;

优化点5(质量)

不好的方案

function getCurrentState() {
//循环1秒调用后端接口返回,再返回true的时候结束调用
 return false
}

let time = setInterval(() => {
   if(getCurrentState()) {
    clearInterval(time);
    //写接下来的逻辑
   }
},1000)

好的方案

function getCurrentState() {
//循环1秒调用后端接口返回,再返回true的时候结束调用
 return false
}

new Promise((relove) => {
  let time = setInterval(() => {
   if(getCurrentState()) {
    clearInterval(time);
    relove('complate.........')
   }
  },1000)
})

//写接下来的逻辑  避免再内部写逻辑

优化点6(质量)

不好的方案

//生成一个避免重复的rgba

let idPoint = {}

functione getIdByRgba() {
  let id = `${Math.ceil(Math.random() * 255)}-${Math.ceil(Math.random() * 255)}-${Math.ceil(Math.random() * 255)}-225`;
  
  while(idPoint[id]) {
    id = `${Math.ceil(Math.random() * 255)}-${Math.ceil(Math.random() * 255)}-${Math.ceil(Math.random() * 255)}-225`;
  }
 
 return id
}

好的方案

let idPoint = {}

function createdRgba() {
 return Array(3)
        .fill(0)
        .map(() => Math.ceil(Math.random() * 255))
        .concat(255)
        .join("-");
}

functione getIdByRgba() {
  let id = createdRgba();
  while(idPoint[id]) {
    id = createdRgba();
  }
  return id
}

优化点7(质量)

不好的方案

  • vueBus相信大家都用过
  • 就是他不会自动解除绑定
  • 并且会重复绑定 会触发多次函数

好的方案

  • 在一个界面beforeDestroy前把所有用到的vueBus销毁 解除绑定
  • 代码如下
const eventContainer = ['a','b','c']
eventContainer.forEach(item => vueBus.off(item));

优化点8 (质量)

不好的方案

  • vue项目中 弹窗组件多个分别绑定不同的变量触发显示隐藏

代码如下:

<template>
<div class='dialog-container'>
     <A :visible.sync='aVisible'/>
     <B :visible.sync='bVisible'/>
     <C :visible.sync='cVisible'/>
     <D :visible.sync='dVisible'/>
</div>
</template>

<script>
import A from './a.vue';
import B from './b.vue';
import C from './c.vue';
import D from './d.vue';

export default {
 components: { A, B, C, D}
 data() {
   return {
     aVisible: false,
     bVisible: false,
     cVisible: false,
     dVisible: false,
   }
 }

}
</script>

好的方案

  • 切换currentComponent就行了 用vue的动态组件
<template>
<div class='dialog-container'>
     <component
      :is="currentComponent"
      :visible.sync="visible"
    />
</div>
</template>

<script>
import A from './a.vue';
import B from './b.vue';
import C from './c.vue';
import D from './d.vue';

export default {
 components: { A, B, C, D}
 data() {
   return {
     currentComponent: 'A',
     visible: false
   }
 }

}
</script>

结束语:

  • 大家好,我是 三原
  • 希望大家变得越来有优秀
  • 有问题大家指出来 一块讨论啊