1 初衷

假如有以下一段代码,render 办法的参数 c 是常常变动的,而 a、b 则变动不频繁。剖析这段代码能够得出一个论断:每次 render 函数被调用都会触发 calc 函数的调用,如果 a、b 参数没有产生扭转,那么就会减少没有必要的计算。

function calc (a, b) {  console.log('calc', a, b)  // 简单的计算  return a ** b}function render (a, b, c) {  console.log('render', a, b, c)  return {    status: c % 10,    result: calc(a, b)  }}

解决这种问题的办法有很多,置信聪慧的你曾经想进去用缓存的办法能够解决这样的问题;这里介绍给大家 Memoize Function 一种解决问题的思路。

2 记忆函数

其原理是通过对函数参数、计算结果进行缓存,再次调用进行比拟:如果参数产生了变动,那么须要进行从新计算;如果参数没有发生变化,则返回上一次的计算结果:

function createMemo (targetFunc) {  let lastArgs = null  let lastResult = null  return function (...args) {    if (!argumentsShallowlyEqual(lastArgs, args)) {            lastResult = targetFunc(...args)    }    lastArgs = args    return lastResult  }}function argumentsShallowlyEqual (prev, next) {  if (prev === null || next === null || prev.length !== next.length) {    return false  }  const length = prev.length  for (let i=0; i<length; i++) {    if (prev[i] !== next[i]) {      return false    }  }  return true}

当初将 calc 办法封装一下再进行测试:

calc = createMemo(calc)render(1,2,3)// render 1 2 3// calc 1 2render(1,2,3)// render 1 2 3render(2,2,3)// render 2 2 3// calc 2 2render(2,2,3)// render 2 2 3

封装的办法 createMemo 拓展性不够,某些状况下,须要精密的管制是否进行缓存,比方函数如果承受一个对象的状况:

function calc (option) {  // 这里耗费大量性能  console.log('calc')}calc({ value: 0 })// calccalc({ value: 0 })// calccalc({ value: 1 })// calc

那么的记忆函数比拟适合的用法法应该是这样的:

const memoizedRender = createMemo(option => option.value, render)memoizedRender()// calcmemoizedRender()memoizedRender()

而后来批改一下 createMemo 办法:

function createMemo (...funcs) {  const targetFunc = funcs.pop()  const dependencies = [...funcs]      const memoizedTargetFunc = defaultMemoize(targetFunc)  const selector = defaultMemoize(function (...args) {    const params = []    const length = dependencies.length        for (let i=0; i<length; i++) {      params.push(dependencies[i](...args))    }    return memoizedTargetFunc(...params)  })  return selector}function defaultMemoize (func) {  let lastArgs = null  let lastResult = null    return function (...args) {    if (!argumentsShallowlyEqual(lastArgs, args)) {      lastResult = func(...args)    }    lastArgs = args    return lastResult  }}function argumentsShallowlyEqual (prev, next) {  if (prev === null || next === null || prev.length !== next.length) {    return false  }  const length = prev.length  for (let i=0; i<length; i++) {    if (prev[i] !== next[i]) {      return false    }  }  return true}
参考

Redux 计算衍生数据:https://www.redux.org.cn/docs...

Reselect https://github.com/reduxjs/re...

在 Vue 中也有计算属性能达到相似成果,他们在实现上和用法都有一些不同

3 Vue computed

3.1 根本用法

const Demo1 = new Vue({  template: '<div>{{b}}</div>',  data () {    return {      a: 1    }  },  computed: {    b () {      return a + 1    }  }})
const Demo2 = new Vue({  template: '<div>{{b}}{{c}}</div>',  data () {    return {      a: 1    }  },  computed: {    b () {      console.log('b')      return a + 1    },    c () {      console.log('c')      return b + a    }  }})

如果这时候扭转 a ,那么 c 、b 计算属性中各打印几次 ?

3.2 原理

实例化一个 Vue 组件大抵经验以下过程,从上面的简化代码能够看出,计算属性 computed 次要在 initComputed 办法中初始化。

https://github.com/vuejs/vue/blob/dev/src/core/instance/index.js#L8function Vue (options) {  this._init(options)}Vue.prototype._init = function (options) {  // ...  // https://github.com/vuejs/vue/blob/dev/src/core/instance/init.js#L52  initLifecycle(vm)  initEvents(vm)  initRender(vm)  callHook(vm, 'beforeCreate')  initInjections(vm) // resolve injections before data/props  initState(vm)}// https://github.com/vuejs/vue/blob/dev/src/core/instance/state.js#L48function initState (vm) {  vm._watchers = []  const opts = vm.$options  if (opts.props) initProps(vm, opts.props)  if (opts.methods) initMethods(vm, opts.methods)  if (opts.data) {    initData(vm)  } else {    observe(vm._data = {}, true /* asRootData */)  }  if (opts.computed) initComputed(vm, opts.computed)  if (opts.watch && opts.watch !== nativeWatch) {    initWatch(vm, opts.watch)  }}

在 computed 初始化阶段,须要留神的是 Vue 遍历 computed 对象,为每个属性实例化一个 lazy Watcher ,而后将每个属性 defineComputed。

const computedWatcherOptions = { lazy: true }function initComputed (vm: Component, computed: Object) {  // $flow-disable-line  const watchers = vm._computedWatchers = Object.create(null)  // computed properties are just getters during SSR  const isSSR = isServerRendering()  for (const key in computed) {    const userDef = computed[key]    const getter = typeof userDef === 'function' ? userDef : userDef.get    if (process.env.NODE_ENV !== 'production' && getter == null) {      warn(        `Getter is missing for computed property "${key}".`,        vm      )    }    if (!isSSR) {      // create internal watcher for the computed property.      watchers[key] = new Watcher(        vm,        getter || noop,        noop,        computedWatcherOptions      )    }    // component-defined computed properties are already defined on the    // component prototype. We only need to define computed properties defined    // at instantiation here.    if (!(key in vm)) {      defineComputed(vm, key, userDef)    } else if (process.env.NODE_ENV !== 'production') {      if (key in vm.$data) {        warn(`The computed property "${key}" is already defined in data.`, vm)      } else if (vm.$options.props && key in vm.$options.props) {        warn(`The computed property "${key}" is already defined as a prop.`, vm)      }    }  }}

先小结一下,计算属性在实例化的时候次要做了:

  1. 遍历每个属性,为每个属性实例化一个 lazy Watcher
  2. 为每个属性 defineComputed

先往下走,看看 defineComputed 做了什么事件

3.2.1 defineComputed

这个过程很简略,相似于将一个对象 defineReactive 。

const sharedPropertyDefinition = {  enumerable: true,  configurable: true,  get: noop,  set: noop}export function defineComputed (  target: any,  key: string,  userDef: Object | Function) {  const shouldCache = !isServerRendering()  if (typeof userDef === 'function') {    sharedPropertyDefinition.get = shouldCache      ? createComputedGetter(key)      : createGetterInvoker(userDef)    sharedPropertyDefinition.set = noop  } else {    sharedPropertyDefinition.get = userDef.get      ? shouldCache && userDef.cache !== false        ? createComputedGetter(key)        : createGetterInvoker(userDef.get)      : noop    sharedPropertyDefinition.set = userDef.set || noop  }  Object.defineProperty(target, key, sharedPropertyDefinition)}function createComputedGetter (key) {  return function computedGetter () {    const watcher = this._computedWatchers && this._computedWatchers[key]    if (watcher) {      if (watcher.dirty) {        watcher.evaluate()      }      if (Dep.target) {        watcher.depend()      }      return watcher.value    }  }}

这里次要关注 computedGetter 办法,在这之前,先来理解一下 watcher 的几个属性办法,前面会具体去说:

  • watcher.dirty 是标记 watcher 是否须要从新求值,当依赖发生变化时 dirty 会被赋值为 true ,因为须要从新求值了
  • watcher.evaluate 所做的事件就是求值,求值实现后将 dirty 赋值为 false
  • watcher.depend 依赖以后的 Dep.target,比方以后正在处于渲染过程中,Darget.target 为渲染 watcher ,那么以后计算属性的 watcher 会被渲染watcher 收集

获取计算属性的值时,会触发 computedGetter 办法,首次调用会触发 watcher.evalute 计算,这两头会有依赖收集的过程;计算实现后,会进行值的缓存,那么计算属性再次被调用就不会触发求值。

到这里你可能有点糊涂,实际上 Watcher 是计算属性实现的要害,像要理解计算属性,必须要深刻 Watcher 的实现。

3.2.2 lazy Watcher

经简化后,与计算属性相干的代码如下:

// https://github.com/vuejs/vue/blob/dev/src/core/observer/watcher.js#L26class Watcher {  constructor(    vm: Component,    expOrFn: string | Function,    cb: Function,    options?: ?Object,    isRenderWatcher?: boolean  ) {        this.vm = vm    this.lazy = !!options.lazy        this.dirty = this.lazy    this.getter = expOrFn    // lazy watcher 不立刻求值    this.value = this.lazy ? undefined : this.get()  }    get () {    pushTarget(this)    let value    value = this.getter.call(vm, vm)    if (this.deep) {      traverse(value)    }    popTarget()    this.cleanupDeps()    return value  }    update () {    /* istanbul ignore else */    // 计算属性的依赖产生更新时    if (this.lazy) {      this.dirty = true    } else if (this.sync) {      this.run()    } else {      queueWatcher(this)    }  }    // 计算属性取值时触发  evaluate () {    this.value = this.get()    this.dirty = false  }}

能够分三个过程来解释这部分代码:Watcher 实例化过程、计算属性取值过程、依赖更新过程

  1. Watcher 实例化过程

计算属性的 lazy 会被复制为 false ,即实例化了一个 lazy Watcher
如果以后是一个 lazy Watcher 的话,那么不会立刻去求值

  1. 计算属性取值过程

当触发计算属性的 computedGetter 取值函数时,会调用 watcher.evaluate 办法,这个办法才真正的调用 getter 函数(也就是开发者定义的 computed 的函数)来计算结果,并将后果缓存到 watcher.value 中

当 watcher.get 被调用时,Dep.target 会变为以后这个计算属性的 watcher ,所以 this.getter 调用的时候,函数外部的所有依赖会被以后 watcher 收集。

这里依赖收集的过程如果你不是很理解的话,举荐你看一下 vue 的 observer 的过程,或者看一下我的另一篇相干的文章 深刻理解 vue 响应式原理

当 watcher.evaluate 调用实现后,dirty 会被立刻设置为 false ,所以后续再触发计算属性的取值函数,则不会从新计算,这样就达到了缓存的成果

  1. 依赖更新的过程

当计算属性的依赖更新时,会触发计算属性 watcher.update 办法,这里并不进行求值,仅仅是将以后的 dirty 赋值为 false 表明以后的 watcher 的依赖曾经发生变化,那么下一次计算属性被调用时,就会触发从新求值。这里就解释了,当计算属性的依赖更新时,计算属性并不会立刻从新计算,而是当调用的时候才会从新求值。

4 总结

以上,本文详细分析了记忆函数与 Vue 的计算属性,Vue 的计算属性很奇妙的联合 Vue 本身响应式个性实现,Redux 也是通过简略的记忆函数就能实现性能优化。

原文: Vue computed 与记忆函数