Redux源码学习之-isPlainObject 函数性能

71 阅读1分钟

前言

怀着对源码的学习之心,开始了对Redux源码的学习,

问题发现

看着看着发现了dispatch中的isPlainObject函数.

image.png 好家伙,必须是普通对象,看看究竟是什么函数,

image.png,

01YJUhwfa4.jpg

心想写的啥竟然涉及到了原型链,大大的不理解,执行效率肯定受到影响吧!干活的机会来啦

e656ef6515.gif

上测试代码

console.time('myTimer');

    function isPlainObject(obj) {
      if (typeof obj !== 'object' || obj === null) return false;

      let proto = obj;
      //使用 while 循环,通过 Object.getPrototypeOf(proto) 获取 proto 对象的原型对象,直到找到原型链的顶层(即原型为 null)
      while (Object.getPrototypeOf(proto) !== null) {
        proto = Object.getPrototypeOf(proto);
      }

      return Object.getPrototypeOf(obj) === proto;
    }
    isPlainObject({});
    console.timeEnd('myTimer');

    console.time('myTimer2');
    Object.prototype.toString.call({}) === '[object Object]';
    console.timeEnd('myTimer2');

    console.time('myTimer3');
    const obj = {};
    typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
    console.timeEnd('myTimer3');

结果

image.png 无论怎么测,性能最差,虽然就差一点点,但对于精益求精的我来说不能忍,

u=2180461952,1393489917&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto.webp