vue3复习-源码-diff算法

225 阅读17分钟

版本

vue 3.4.20

关键方法

patch

回顾一下,patch方法主要判断当前组件的类型,做不同的处理

  • processText 更新文本
  • processFragment 处理根组件 patchChildren 处理子组件
  • processElement 处理html 同时调用mountChildren/patchChildren 处理子组件
  • processComponent 处理组件, 同时调用mountComponent/updateComponent 创建effect依赖收集,
const patch: PatchFn = (
    n1,
    n2,
    container,
    anchor = null,
    parentComponent = null,
    parentSuspense = null,
    namespace = undefined,
    slotScopeIds = null,
    optimized = __DEV__ && isHmrUpdating ? false : !!n2.dynamicChildren,
  ) => {
    if (n1 === n2) {
      return
    }

    // patching & not same type, unmount old tree
    if (n1 && !isSameVNodeType(n1, n2)) {
      anchor = getNextHostNode(n1)
      unmount(n1, parentComponent, parentSuspense, true)
      n1 = null
    }

    if (n2.patchFlag === PatchFlags.BAIL) {
      optimized = false
      n2.dynamicChildren = null
    }

    const { type, ref, shapeFlag } = n2
    switch (type) {
      case Text:
        processText(n1, n2, container, anchor)
        break
      case Comment:
        processCommentNode(n1, n2, container, anchor)
        break
      case Static:
        if (n1 == null) {
          mountStaticNode(n2, container, anchor, namespace)
        } else if (__DEV__) {
          patchStaticNode(n1, n2, container, namespace)
        }
        break
      case Fragment:
        processFragment(
          n1,
          n2,
          container,
          anchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized,
        )
        break
      default:
        if (shapeFlag & ShapeFlags.ELEMENT) {
          processElement(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
        } else if (shapeFlag & ShapeFlags.COMPONENT) {
          processComponent(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
        } else if (shapeFlag & ShapeFlags.TELEPORT) {
          ;(type as typeof TeleportImpl).process(
            n1 as TeleportVNode,
            n2 as TeleportVNode,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
            internals,
          )
        } else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
          ;(type as typeof SuspenseImpl).process(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
            internals,
          )
        } else if (__DEV__) {
          warn('Invalid VNode type:', type, `(${typeof type})`)
        }
    }

    // set ref
    if (ref != null && parentComponent) {
      setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2)
    }
  }

这里我们也看到vue3 通过位运算 优化组件类型判断

export enum ShapeFlags {
  ELEMENT = 1,
  FUNCTIONAL_COMPONENT = 1 << 1,
  STATEFUL_COMPONENT = 1 << 2,
  TEXT_CHILDREN = 1 << 3,
  ARRAY_CHILDREN = 1 << 4,
  SLOTS_CHILDREN = 1 << 5,
  TELEPORT = 1 << 6,
  SUSPENSE = 1 << 7,
  COMPONENT_SHOULD_KEEP_ALIVE = 1 << 8,
  COMPONENT_KEPT_ALIVE = 1 << 9,
  COMPONENT = ShapeFlags.STATEFUL_COMPONENT | ShapeFlags.FUNCTIONAL_COMPONENT,
}



 if (shapeFlag & ShapeFlags.ELEMENT) {
          processElement(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
        } else if (shapeFlag & ShapeFlags.COMPONENT) {
          processComponent(
            n1,
            n2,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
        } else if (shapeFlag & ShapeFlags.TELEPORT) {
          ;(type as typeof TeleportImpl).process(
            n1 as TeleportVNode,
            n2 as TeleportVNode,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
            internals,
          )
        } else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
        ...
        }

条件判断

求与

当当前的shapeFlag 为ELEMENT为1 ,即与ShapeFlags.ELEMENT判断 为真,

0001
0001 &
0001

如果shapeFlag为TELEPORT,与ShapeFlags.ELEMENT判断 为假

000001
100000 &
000000

求或

组件比较特殊含有两个权限,可以利用或运算 取交集


FUNCTIONAL_COMPONENT = 1 << 1,
STATEFUL_COMPONENT = 1 << 2,
COMPONENT = ShapeFlags.STATEFUL_COMPONENT | ShapeFlags.FUNCTIONAL_COMPONENT,


0010
01000110

所以判断组件也只需要判断0110求与即可

当当前的shapeFlag 为ELEMENT为1 ,为假,权限不存在

0110
0001 &
0000 

当当前的shapeFlag 为COMPONENT为1 ,为真,权限存在

0110
0110 &
0110 

diff发生的地方

diff算法发生在数据更新,所以我们要关注一下processFragment和processElement

  • processFragment 处理根组件 patchChildren 处理子组件
  • processElement 处理html patchChildren 处理子组件

processFragment

  const processFragment = (
    n1: VNode | null,
    n2: VNode,
    container: RendererElement,
    anchor: RendererNode | null,
    parentComponent: ComponentInternalInstance | null,
    parentSuspense: SuspenseBoundary | null,
    namespace: ElementNamespace,
    slotScopeIds: string[] | null,
    optimized: boolean,
  ) => {
    const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''))!
    const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''))!

    let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2

    if (
      __DEV__ &&
      // #5523 dev root fragment may inherit directives
      (isHmrUpdating || patchFlag & PatchFlags.DEV_ROOT_FRAGMENT)
    ) {
      // HMR updated / Dev root fragment (w/ comments), force full diff
      patchFlag = 0
      optimized = false
      dynamicChildren = null
    }

    // check if this is a slot fragment with :slotted scope ids
    if (fragmentSlotScopeIds) {
      slotScopeIds = slotScopeIds
        ? slotScopeIds.concat(fragmentSlotScopeIds)
        : fragmentSlotScopeIds
    }

    if (n1 == null) {
      hostInsert(fragmentStartAnchor, container, anchor)
      hostInsert(fragmentEndAnchor, container, anchor)
      // a fragment can only have array children
      // since they are either generated by the compiler, or implicitly created
      // from arrays.
      mountChildren(
        // #10007
        // such fragment like `<></>` will be compiled into
        // a fragment which doesn't have a children.
        // In this case fallback to an empty array
        (n2.children || []) as VNodeArrayChildren,
        container,
        fragmentEndAnchor,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized,
      )
    } else {
      if (
        patchFlag > 0 &&
        patchFlag & PatchFlags.STABLE_FRAGMENT &&
        dynamicChildren &&
        // #2715 the previous fragment could've been a BAILed one as a result
        // of renderSlot() with no valid children
        n1.dynamicChildren
      ) {
        // a stable fragment (template root or <template v-for>) doesn't need to
        // patch children order, but it may contain dynamicChildren.
        patchBlockChildren(
          n1.dynamicChildren,
          dynamicChildren,
          container,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
        )
        if (__DEV__) {
          // necessary for HMR
          traverseStaticChildren(n1, n2)
        } else if (
          // #2080 if the stable fragment has a key, it's a <template v-for> that may
          //  get moved around. Make sure all root level vnodes inherit el.
          // #2134 or if it's a component root, it may also get moved around
          // as the component is being moved.
          n2.key != null ||
          (parentComponent && n2 === parentComponent.subTree)
        ) {
          traverseStaticChildren(n1, n2, true /* shallow */)
        }
      } else {
        // keyed / unkeyed, or manual fragments.
        // for keyed & unkeyed, since they are compiler generated from v-for,
        // each child is guaranteed to be a block so the fragment will never
        // have dynamicChildren.
        patchChildren(
          n1,
          n2,
          container,
          fragmentEndAnchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized,
        )
      }
    }
  }

在更新的逻辑里面最终会被执行 patchBlockChildren/patchChildren (patchBlockChildren作为优化暂不分析)

processElement

最终调用判断为更新走 patchElement,然后还是调用了 patchChildren

  const processElement = (
    n1: VNode | null,
    n2: VNode,
    container: RendererElement,
    anchor: RendererNode | null,
    parentComponent: ComponentInternalInstance | null,
    parentSuspense: SuspenseBoundary | null,
    namespace: ElementNamespace,
    slotScopeIds: string[] | null,
    optimized: boolean,
  ) => {
    if (n2.type === 'svg') {
      namespace = 'svg'
    } else if (n2.type === 'math') {
      namespace = 'mathml'
    }

    if (n1 == null) {
      mountElement(
        n2,
        container,
        anchor,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized,
      )
    } else {
      patchElement(
        n1,
        n2,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized,
      )
    }
  }
  
  
  const patchElement = (
    n1: VNode,
    n2: VNode,
    parentComponent: ComponentInternalInstance | null,
    parentSuspense: SuspenseBoundary | null,
    namespace: ElementNamespace,
    slotScopeIds: string[] | null,
    optimized: boolean,
  ) => {
    const el = (n2.el = n1.el!)
    if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
      el.__vnode = n2
    }
    let { patchFlag, dynamicChildren, dirs } = n2
    // #1426 take the old vnode's patch flag into account since user may clone a
    // compiler-generated vnode, which de-opts to FULL_PROPS
    patchFlag |= n1.patchFlag & PatchFlags.FULL_PROPS
    const oldProps = n1.props || EMPTY_OBJ
    const newProps = n2.props || EMPTY_OBJ
    let vnodeHook: VNodeHook | undefined | null

    // disable recurse in beforeUpdate hooks
    parentComponent && toggleRecurse(parentComponent, false)
    if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
      invokeVNodeHook(vnodeHook, parentComponent, n2, n1)
    }
    if (dirs) {
      invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate')
    }
    parentComponent && toggleRecurse(parentComponent, true)

    if (__DEV__ && isHmrUpdating) {
      // HMR updated, force full diff
      patchFlag = 0
      optimized = false
      dynamicChildren = null
    }

    if (dynamicChildren) {
      patchBlockChildren(
        n1.dynamicChildren!,
        dynamicChildren,
        el,
        parentComponent,
        parentSuspense,
        resolveChildrenNamespace(n2, namespace),
        slotScopeIds,
      )
      if (__DEV__) {
        // necessary for HMR
        traverseStaticChildren(n1, n2)
      }
    } else if (!optimized) {
      // full diff
      patchChildren(
        n1,
        n2,
        el,
        null,
        parentComponent,
        parentSuspense,
        resolveChildrenNamespace(n2, namespace),
        slotScopeIds,
        false,
      )
    }

    if (patchFlag > 0) {
      // the presence of a patchFlag means this element's render code was
      // generated by the compiler and can take the fast path.
      // in this path old node and new node are guaranteed to have the same shape
      // (i.e. at the exact same position in the source template)
      if (patchFlag & PatchFlags.FULL_PROPS) {
        // element props contain dynamic keys, full diff needed
        patchProps(
          el,
          n2,
          oldProps,
          newProps,
          parentComponent,
          parentSuspense,
          namespace,
        )
      } else {
        // class
        // this flag is matched when the element has dynamic class bindings.
        if (patchFlag & PatchFlags.CLASS) {
          if (oldProps.class !== newProps.class) {
            hostPatchProp(el, 'class', null, newProps.class, namespace)
          }
        }

        // style
        // this flag is matched when the element has dynamic style bindings
        if (patchFlag & PatchFlags.STYLE) {
          hostPatchProp(el, 'style', oldProps.style, newProps.style, namespace)
        }

        // props
        // This flag is matched when the element has dynamic prop/attr bindings
        // other than class and style. The keys of dynamic prop/attrs are saved for
        // faster iteration.
        // Note dynamic keys like :[foo]="bar" will cause this optimization to
        // bail out and go through a full diff because we need to unset the old key
        if (patchFlag & PatchFlags.PROPS) {
          // if the flag is present then dynamicProps must be non-null
          const propsToUpdate = n2.dynamicProps!
          for (let i = 0; i < propsToUpdate.length; i++) {
            const key = propsToUpdate[i]
            const prev = oldProps[key]
            const next = newProps[key]
            // #1471 force patch value
            if (next !== prev || key === 'value') {
              hostPatchProp(
                el,
                key,
                prev,
                next,
                namespace,
                n1.children as VNode[],
                parentComponent,
                parentSuspense,
                unmountChildren,
              )
            }
          }
        }
      }

      // text
      // This flag is matched when the element has only dynamic text children.
      if (patchFlag & PatchFlags.TEXT) {
        if (n1.children !== n2.children) {
          hostSetElementText(el, n2.children as string)
        }
      }
    } else if (!optimized && dynamicChildren == null) {
      // unoptimized, full diff
      patchProps(
        el,
        n2,
        oldProps,
        newProps,
        parentComponent,
        parentSuspense,
        namespace,
      )
    }

    if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
      queuePostRenderEffect(() => {
        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1)
        dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated')
      }, parentSuspense)
    }
  }

重点方法 patchChildren

根据前后不同的状态处理 新老子元素对比:

三个状态

  • 文本
  • 数组

交叉9种情况

image.png 关键复杂的就是 老元素为数组,新元素也为数组情况

  • 如果有标记key 使用patchKeyedChildren,
  • 没有则使用patchUnkeyedChildren

  const patchChildren: PatchChildrenFn = (
    n1,
    n2,
    container,
    anchor,
    parentComponent,
    parentSuspense,
    namespace: ElementNamespace,
    slotScopeIds,
    optimized = false,
  ) => {
    const c1 = n1 && n1.children
    const prevShapeFlag = n1 ? n1.shapeFlag : 0
    const c2 = n2.children

    const { patchFlag, shapeFlag } = n2
    // fast path
    if (patchFlag > 0) {
      if (patchFlag & PatchFlags.KEYED_FRAGMENT) {
        // this could be either fully-keyed or mixed (some keyed some not)
        // presence of patchFlag means children are guaranteed to be arrays
        patchKeyedChildren(
          c1 as VNode[],
          c2 as VNodeArrayChildren,
          container,
          anchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized,
        )
        return
      } else if (patchFlag & PatchFlags.UNKEYED_FRAGMENT) {
        // unkeyed
        patchUnkeyedChildren(
          c1 as VNode[],
          c2 as VNodeArrayChildren,
          container,
          anchor,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized,
        )
        return
      }
    }

    // children has 3 possibilities: text, array or no children.
    if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
      // text children fast path
      if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
        unmountChildren(c1 as VNode[], parentComponent, parentSuspense)
      }
      if (c2 !== c1) {
        hostSetElementText(container, c2 as string)
      }
    } else {
      if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
        // prev children was array
        if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
          // two arrays, cannot assume anything, do full diff
          patchKeyedChildren(
            c1 as VNode[],
            c2 as VNodeArrayChildren,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
        } else {
          // no new children, just unmount old
          unmountChildren(c1 as VNode[], parentComponent, parentSuspense, true)
        }
      } else {
        // prev children was text OR null
        // new children is array OR null
        if (prevShapeFlag & ShapeFlags.TEXT_CHILDREN) {
          hostSetElementText(container, '')
        }
        // mount new if array
        if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
          mountChildren(
            c2 as VNodeArrayChildren,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
        }
      }
    }
  }

patchUnkeyedChildren

先看patchUnkeyedChildren 没有key ,很简单直接patch所有节点。


  const patchUnkeyedChildren = (
    c1: VNode[],
    c2: VNodeArrayChildren,
    container: RendererElement,
    anchor: RendererNode | null,
    parentComponent: ComponentInternalInstance | null,
    parentSuspense: SuspenseBoundary | null,
    namespace: ElementNamespace,
    slotScopeIds: string[] | null,
    optimized: boolean,
  ) => {
    c1 = c1 || EMPTY_ARR
    c2 = c2 || EMPTY_ARR
    const oldLength = c1.length
    const newLength = c2.length
    const commonLength = Math.min(oldLength, newLength)
    let i
    for (i = 0; i < commonLength; i++) {
      const nextChild = (c2[i] = optimized
        ? cloneIfMounted(c2[i] as VNode)
        : normalizeVNode(c2[i]))
      patch(
        c1[i],
        nextChild,
        container,
        null,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized,
      )
    }
    if (oldLength > newLength) {
      // remove old
      unmountChildren(
        c1,
        parentComponent,
        parentSuspense,
        true,
        false,
        commonLength,
      )
    } else {
      // mount new
      mountChildren(
        c2,
        container,
        anchor,
        parentComponent,
        parentSuspense,
        namespace,
        slotScopeIds,
        optimized,
        commonLength,
      )
    }
  }

patchKeyedChildren

最复杂的diff算法。里面包含 两头比较,双游标移动,最长递增子序列。

1.网页局部更新假说
  • 也就是我们认为一般网页,大多数都是顶行或结尾修改多。
  • 所以我们可以针对先头头比较,头尾比较优先判断
2.双游标移动
  • 新老数组都创建一个左游标和右游标
  • 每次处理完vnode,都往中间靠近
  • 最后如果右边游标小于左边游标,则停止。
  • 把剩下的未判断的节点做 新增或移除。
3.最长递增子序列
  • 在一个列表里面,把最连续的一个小数组给找出来。
  • 然后固定这个小数组,只移动剩下的节点。
  • 由于新老数组也是数组,下标原来就包含了顺序的关系。
  • getSequence方法是实现的逻辑

  // can be all-keyed or mixed
  const patchKeyedChildren = (
    c1: VNode[],
    c2: VNodeArrayChildren,
    container: RendererElement,
    parentAnchor: RendererNode | null,
    parentComponent: ComponentInternalInstance | null,
    parentSuspense: SuspenseBoundary | null,
    namespace: ElementNamespace,
    slotScopeIds: string[] | null,
    optimized: boolean,
  ) => {
    let i = 0
    const l2 = c2.length
    let e1 = c1.length - 1 // prev ending index
    let e2 = l2 - 1 // next ending index

    // 1. sync from start
    // (a b) c
    // (a b) d e
    while (i <= e1 && i <= e2) {
      const n1 = c1[i]
      const n2 = (c2[i] = optimized
        ? cloneIfMounted(c2[i] as VNode)
        : normalizeVNode(c2[i]))
      if (isSameVNodeType(n1, n2)) {
        patch(
          n1,
          n2,
          container,
          null,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized,
        )
      } else {
        break
      }
      i++
    }

    // 2. sync from end
    // a (b c)
    // d e (b c)
    while (i <= e1 && i <= e2) {
      const n1 = c1[e1]
      const n2 = (c2[e2] = optimized
        ? cloneIfMounted(c2[e2] as VNode)
        : normalizeVNode(c2[e2]))
      if (isSameVNodeType(n1, n2)) {
        patch(
          n1,
          n2,
          container,
          null,
          parentComponent,
          parentSuspense,
          namespace,
          slotScopeIds,
          optimized,
        )
      } else {
        break
      }
      e1--
      e2--
    }

    // 3. common sequence + mount
    // (a b)
    // (a b) c
    // i = 2, e1 = 1, e2 = 2
    // (a b)
    // c (a b)
    // i = 0, e1 = -1, e2 = 0
    if (i > e1) {
      if (i <= e2) {
        const nextPos = e2 + 1
        const anchor = nextPos < l2 ? (c2[nextPos] as VNode).el : parentAnchor
        while (i <= e2) {
          patch(
            null,
            (c2[i] = optimized
              ? cloneIfMounted(c2[i] as VNode)
              : normalizeVNode(c2[i])),
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
          i++
        }
      }
    }

    // 4. common sequence + unmount
    // (a b) c
    // (a b)
    // i = 2, e1 = 2, e2 = 1
    // a (b c)
    // (b c)
    // i = 0, e1 = 0, e2 = -1
    else if (i > e2) {
      while (i <= e1) {
        unmount(c1[i], parentComponent, parentSuspense, true)
        i++
      }
    }

    // 5. unknown sequence
    // [i ... e1 + 1]: a b [c d e] f g
    // [i ... e2 + 1]: a b [e d c h] f g
    // i = 2, e1 = 4, e2 = 5
    else {
      const s1 = i // prev starting index
      const s2 = i // next starting index

      // 5.1 build key:index map for newChildren
      const keyToNewIndexMap: Map<PropertyKey, number> = new Map()
      for (i = s2; i <= e2; i++) {
        const nextChild = (c2[i] = optimized
          ? cloneIfMounted(c2[i] as VNode)
          : normalizeVNode(c2[i]))
        if (nextChild.key != null) {
          if (__DEV__ && keyToNewIndexMap.has(nextChild.key)) {
            warn(
              `Duplicate keys found during update:`,
              JSON.stringify(nextChild.key),
              `Make sure keys are unique.`,
            )
          }
          keyToNewIndexMap.set(nextChild.key, i)
        }
      }

      // 5.2 loop through old children left to be patched and try to patch
      // matching nodes & remove nodes that are no longer present
      let j
      let patched = 0
      const toBePatched = e2 - s2 + 1
      let moved = false
      // used to track whether any node has moved
      let maxNewIndexSoFar = 0
      // works as Map<newIndex, oldIndex>
      // Note that oldIndex is offset by +1
      // and oldIndex = 0 is a special value indicating the new node has
      // no corresponding old node.
      // used for determining longest stable subsequence
      const newIndexToOldIndexMap = new Array(toBePatched)
      for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0

      for (i = s1; i <= e1; i++) {
        const prevChild = c1[i]
        if (patched >= toBePatched) {
          // all new children have been patched so this can only be a removal
          unmount(prevChild, parentComponent, parentSuspense, true)
          continue
        }
        let newIndex
        if (prevChild.key != null) {
          newIndex = keyToNewIndexMap.get(prevChild.key)
        } else {
          // key-less node, try to locate a key-less node of the same type
          for (j = s2; j <= e2; j++) {
            if (
              newIndexToOldIndexMap[j - s2] === 0 &&
              isSameVNodeType(prevChild, c2[j] as VNode)
            ) {
              newIndex = j
              break
            }
          }
        }
        if (newIndex === undefined) {
          unmount(prevChild, parentComponent, parentSuspense, true)
        } else {
          newIndexToOldIndexMap[newIndex - s2] = i + 1
          if (newIndex >= maxNewIndexSoFar) {
            maxNewIndexSoFar = newIndex
          } else {
            moved = true
          }
          patch(
            prevChild,
            c2[newIndex] as VNode,
            container,
            null,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
          patched++
        }
      }

      // 5.3 move and mount
      // generate longest stable subsequence only when nodes have moved
      const increasingNewIndexSequence = moved
        ? getSequence(newIndexToOldIndexMap)
        : EMPTY_ARR
      j = increasingNewIndexSequence.length - 1
      // looping backwards so that we can use last patched node as anchor
      for (i = toBePatched - 1; i >= 0; i--) {
        const nextIndex = s2 + i
        const nextChild = c2[nextIndex] as VNode
        const anchor =
          nextIndex + 1 < l2 ? (c2[nextIndex + 1] as VNode).el : parentAnchor
        if (newIndexToOldIndexMap[i] === 0) {
          // mount new
          patch(
            null,
            nextChild,
            container,
            anchor,
            parentComponent,
            parentSuspense,
            namespace,
            slotScopeIds,
            optimized,
          )
        } else if (moved) {
          // move if:
          // There is no stable subsequence (e.g. a reverse)
          // OR current node is not among the stable sequence
          if (j < 0 || i !== increasingNewIndexSequence[j]) {
            move(nextChild, container, anchor, MoveType.REORDER)
          } else {
            j--
          }
        }
      }
    }
  }
  
  
// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
function getSequence(arr: number[]): number[] {
  const p = arr.slice()
  const result = [0]
  let i, j, u, v, c
  const len = arr.length
  for (i = 0; i < len; i++) {
    const arrI = arr[i]
    if (arrI !== 0) {
      j = result[result.length - 1]
      if (arr[j] < arrI) {
        p[i] = j
        result.push(i)
        continue
      }
      u = 0
      v = result.length - 1
      while (u < v) {
        c = (u + v) >> 1
        if (arr[result[c]] < arrI) {
          u = c + 1
        } else {
          v = c
        }
      }
      if (arrI < arr[result[u]]) {
        if (u > 0) {
          p[i] = result[u - 1]
        }
        result[u] = i
      }
    }
  }
  u = result.length
  v = result[u - 1]
  while (u-- > 0) {
    result[u] = v
    v = p[v]
  }
  return result
}

自己实现diff

使用这个算法主要用处是,当diff 算法已经比较剩下两个数组时候,原来[1,2,3,4,5,6]. 调整后 变成 [1,3,4,2,6,5] 这时候要找到最优的移动方案。

image.png

  • 最差的方案就是每个元素都更新。
  • 最优的移动方案就是 只移动 2和5 ,2移动到4后,5 移动到6后。
    那么要只移动 2和5。就要确定 1,3,4,6 是固定不变的,也称为当前数组的最长的递增子序列。

因为原来就是使用数组为下标,所以已经是从小到大排列。只是局部乱了。所以找出局部错乱的是较优的策略。

leetcode.cn/problems/lo…
leetcode只查询长度,当前vue3需要确定的数组 代码如下

var getSequence1 = function (nums) {
    let result = []
    for (let i = 0; i < nums.length; i++) {
      let last = nums[result[result.length - 1]],
        current = nums[i]
      if (current > last || last === undefined) {
        // 当前项大于最后一项
        result.push(i)
      } else {
        // 当前项小于最后一项,二分查找+替换
        let start = 0,
          end = result.length - 1,
          middle
        while (start < end) {
          middle = Math.floor((start + end) / 2)
          if (nums[result[middle]] > current) {
            end = middle
          } else {
            start = middle + 1
          }
        }
        result[start] = i
      }
    }
    return result
  }
  console.log( getSequence1([10,1,2,5,3,7,101,18]))

补充知识

递推

动态规划,通过递推的方式找出最大长度,算法复杂度是 O(n2)


const lengthOfLIS = function(nums) {
    let n = nums.length;
    if (n == 0) {
        return 0;
    }
    let dp = new Array(n).fill(1);
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < i; j++) {
            if (nums[j] < nums[i]) {
                dp[i] = Math.max(dp[i], dp[j] + 1);
            }
        }
    }
    return Math.max(...dp) 
}

贪心算法

贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,算法得到的是在某种意义上的局部最优解。

二分查找

二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。

二分查找之所以快是因为它只需检查很少几个条目(相对于数组的大小)就能够找到目标元素,或者是确认目标元素不存在。

const searchInsert = (nums, target) => {
  let low = 0,
    high = nums.length - 1,
    mid;
  while (low <= high) {
    mid = (low + high) >> 1;
    if (target < nums[mid]) {
      high = mid - 1;
    } else if (target > nums[mid]) {
      low = mid + 1;
    } else {
      return mid;
    }
  }
}; 

完整的DIFF代码

我们基于vitest做测试

vue-diff.js

import { vi, describe, it, expect } from 'vitest';

describe("数组Diff", () => {
    it("1. 左边查找", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [{ key: "a" }, { key: "b" }, { key: "c" }],
        [{ key: "a" }, { key: "b" }, { key: "d" }, { key: "e" }],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      // 第一次调用次数
      expect(patch.mock.calls.length).toBe(2);
      // 第一次调用的第一个参数
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
    });
    it("2. 右边边查找", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [{ key: "a" }, { key: "b" }, { key: "c" }],
        [{ key: "d" }, { key: "e" }, { key: "b" }, { key: "c" }],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      expect(patch.mock.calls.length).toBe(2);
      expect(patch.mock.calls[0][0]).toBe("c");
      expect(patch.mock.calls[1][0]).toBe("b");
    });
    it("3. 老节点没了,新节点还有", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [{ key: "a" }, { key: "b" }],
        [{ key: "a" }, { key: "b" }, { key: "c" }],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      expect(patch.mock.calls.length).toBe(2);
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
      expect(mountElement.mock.calls[0][0]).toBe("c");
    });
    it("4. 老节点还有,新节点没了", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [{ key: "a" }, { key: "b" }, { key: "c" }],
        [{ key: "a" }, { key: "b" }],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      // 第一次调用次数
      expect(patch.mock.calls.length).toBe(2);
      // 第一次调用的第一个参数
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
      expect(unmount.mock.calls[0][0]).toBe("c");
    });
    it("5. 新老节点都有,但是顺序不稳定", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [
          { key: "a" },
          { key: "b" },
          { key: "c" },
          { key: "d" },
          { key: "e" },
          { key: "f" },
          { key: "g" },
        ],
        [
          { key: "a" },
          { key: "b" },
          { key: "e" },
          { key: "d" },
          { key: "c" },
          { key: "h" },
          { key: "f" },
          { key: "g" },
        ],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      // 第一次调用次数
      expect(patch.mock.calls.length).toBe(7);
      // 第一次调用的第一个参数
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
      expect(patch.mock.calls[2][0]).toBe("g");
      expect(patch.mock.calls[3][0]).toBe("f");
      expect(patch.mock.calls[4][0]).toBe("c");
      expect(patch.mock.calls[5][0]).toBe("d");
      expect(patch.mock.calls[6][0]).toBe("e");
      expect(unmount.mock.calls.length).toBe(0);
      //                 0 1  2 3 4  5 6
      // [i ... e1 + 1]: a b [c d e] f g
      // [i ... e2 + 1]: a b [e d c h] f g
      //                      4 3 2 0
      //                      [5 4 3 0]
      // e d c
      // e d c
      // todo
      // 1. mount
      expect(mountElement.mock.calls[0][0]).toBe("h");
      // // 2. move
      expect(move.mock.calls[0][0]).toBe("d");
      expect(move.mock.calls[1][0]).toBe("e");
    });
    it("6. 新老节点都有,但是顺序不稳定", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [
          { key: "a" },
          { key: "b" },
  
          { key: "c" },
          { key: "d" },
          { key: "e" },
  
          { key: "f" },
          { key: "g" },
        ],
        [
          { key: "a" },
          { key: "b" },
  
          { key: "d1" },
          { key: "e" },
          { key: "c" },
          { key: "d" },
          { key: "h" },
  
          { key: "f" },
          { key: "g" },
        ],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      // 第一次调用次数
      expect(patch.mock.calls.length).toBe(7);
      // 第一次调用的第一个参数
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
  
      expect(patch.mock.calls[2][0]).toBe("g");
      expect(patch.mock.calls[3][0]).toBe("f");
  
      expect(patch.mock.calls[4][0]).toBe("c");
      expect(patch.mock.calls[5][0]).toBe("d");
      expect(patch.mock.calls[6][0]).toBe("e");
      expect(unmount.mock.calls.length).toBe(0);
      //                 0 1  2 3 4  5 6
      // [i ... e1 + 1]: a b [c d e] f g
      // [i ... e2 + 1]: a b [e c d h] f g
      // 真实下标         0 1  2 3 4 5  6 7
      // 相对下标              0 1 2 3
      // 下标是新元素的相对下标,value是老元素的下标+1
      //                     [5,3,4,0]
      // todo
      // 1. mount
      expect(mountElement.mock.calls[0][0]).toBe("h");
      expect(mountElement.mock.calls[1][0]).toBe("d1");
  
      // 2. move
      expect(move.mock.calls[0][0]).toBe("e");
    });
  });

测试用例

test/vue-diff.spec.js

import { vi, describe, it, expect } from 'vitest';

describe("数组Diff", () => {
    it("1. 左边查找", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [{ key: "a" }, { key: "b" }, { key: "c" }],
        [{ key: "a" }, { key: "b" }, { key: "d" }, { key: "e" }],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      // 第一次调用次数
      expect(patch.mock.calls.length).toBe(2);
      // 第一次调用的第一个参数
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
    });
    it("2. 右边边查找", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [{ key: "a" }, { key: "b" }, { key: "c" }],
        [{ key: "d" }, { key: "e" }, { key: "b" }, { key: "c" }],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      expect(patch.mock.calls.length).toBe(2);
      expect(patch.mock.calls[0][0]).toBe("c");
      expect(patch.mock.calls[1][0]).toBe("b");
    });
    it("3. 老节点没了,新节点还有", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [{ key: "a" }, { key: "b" }],
        [{ key: "a" }, { key: "b" }, { key: "c" }],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      expect(patch.mock.calls.length).toBe(2);
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
      expect(mountElement.mock.calls[0][0]).toBe("c");
    });
    it("4. 老节点还有,新节点没了", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [{ key: "a" }, { key: "b" }, { key: "c" }],
        [{ key: "a" }, { key: "b" }],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      // 第一次调用次数
      expect(patch.mock.calls.length).toBe(2);
      // 第一次调用的第一个参数
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
      expect(unmount.mock.calls[0][0]).toBe("c");
    });
    it("5. 新老节点都有,但是顺序不稳定", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [
          { key: "a" },
          { key: "b" },
          { key: "c" },
          { key: "d" },
          { key: "e" },
          { key: "f" },
          { key: "g" },
        ],
        [
          { key: "a" },
          { key: "b" },
          { key: "e" },
          { key: "d" },
          { key: "c" },
          { key: "h" },
          { key: "f" },
          { key: "g" },
        ],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      // 第一次调用次数
      expect(patch.mock.calls.length).toBe(7);
      // 第一次调用的第一个参数
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
      expect(patch.mock.calls[2][0]).toBe("g");
      expect(patch.mock.calls[3][0]).toBe("f");
      expect(patch.mock.calls[4][0]).toBe("c");
      expect(patch.mock.calls[5][0]).toBe("d");
      expect(patch.mock.calls[6][0]).toBe("e");
      expect(unmount.mock.calls.length).toBe(0);
      //                 0 1  2 3 4  5 6
      // [i ... e1 + 1]: a b [c d e] f g
      // [i ... e2 + 1]: a b [e d c h] f g
      //                      4 3 2 0
      //                      [5 4 3 0]
      // e d c
      // e d c
      // todo
      // 1. mount
      expect(mountElement.mock.calls[0][0]).toBe("h");
      // // 2. move
      expect(move.mock.calls[0][0]).toBe("d");
      expect(move.mock.calls[1][0]).toBe("e");
    });
    it("6. 新老节点都有,但是顺序不稳定", () => {
      const mountElement = vi.fn();
      const patch = vi.fn();
      const unmount = vi.fn();
      const move = vi.fn();
      const { diffArray } = require("../vue-diff");
      diffArray(
        [
          { key: "a" },
          { key: "b" },
  
          { key: "c" },
          { key: "d" },
          { key: "e" },
  
          { key: "f" },
          { key: "g" },
        ],
        [
          { key: "a" },
          { key: "b" },
  
          { key: "d1" },
          { key: "e" },
          { key: "c" },
          { key: "d" },
          { key: "h" },
  
          { key: "f" },
          { key: "g" },
        ],
        {
          mountElement,
          patch,
          unmount,
          move,
        }
      );
      // 第一次调用次数
      expect(patch.mock.calls.length).toBe(7);
      // 第一次调用的第一个参数
      expect(patch.mock.calls[0][0]).toBe("a");
      expect(patch.mock.calls[1][0]).toBe("b");
  
      expect(patch.mock.calls[2][0]).toBe("g");
      expect(patch.mock.calls[3][0]).toBe("f");
  
      expect(patch.mock.calls[4][0]).toBe("c");
      expect(patch.mock.calls[5][0]).toBe("d");
      expect(patch.mock.calls[6][0]).toBe("e");
      expect(unmount.mock.calls.length).toBe(0);
      //                 0 1  2 3 4  5 6
      // [i ... e1 + 1]: a b [c d e] f g
      // [i ... e2 + 1]: a b [e c d h] f g
      // 真实下标         0 1  2 3 4 5  6 7
      // 相对下标              0 1 2 3
      // 下标是新元素的相对下标,value是老元素的下标+1
      //                     [5,3,4,0]
      // todo
      // 1. mount
      expect(mountElement.mock.calls[0][0]).toBe("h");
      expect(mountElement.mock.calls[1][0]).toBe("d1");
  
      // 2. move
      expect(move.mock.calls[0][0]).toBe("e");
    });
  });

参考

玩转vue3