React与Vue DOM diff区别对比

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React与Vue DOM diff区别对比

隔壁老网   2022-09-29 我要评论

React DOM diff 和 Vue DOM diff 的区别

React 是从左向右遍历对比,Vue 是双端交叉对比。

React 需要维护三个变量(我看源码发现是五个变量),Vue 则需要维护四个变量。

  • Vue 整体效率比 React 更高,举例说明:假设有 N 个子节点,我们只是把最后子节点移到第一个,那么
  • React 需要进行借助 Map 进行 key 搜索找到匹配项,然后复用节点
  • Vue 会发现移动,直接复用节点

React DOM diff 代码查看流程

  • 运行 git clone https://github.com/facebook/react.git
  • 运行 cd react; git switch 17.0.2
  • 用 VSCode 或 WebStorm 打开 react 目录
  • 打开 packages/react-reconciler/src/ReactChildFiber.old.js 第 1274 行查看旧版代码,或打开 packages/react-reconciler/src/ReactChildFiber.new.js 第 1267 行查看新代码(实际上一样) 发现react的源码很多的new和old文件,而且new和old代码几乎一模一样
发现比较经典的注释
// This algorithm can't optimize by searching from both ends since we
    该算法不能通过双端搜索来优化,因为我们
// don't have backpointers on fibers. I'm trying to see how far we can get
    不要在fibers上有反向指针。 我想看看我们能走多远
// with that model. If it ends up not being worth the tradeoffs, we can
    xxx 如果最终需要为此付出代价,我们可以
// add it later.
    以后添加它
// Even with a two ended optimization, we'd want to optimize for the case
    即使是双端优化,我们也要针对这种情况进行优化
// where there are few changes and brute force the comparison instead of
    哪里有一些变化和暴力比较而不是
// going for the Map. It'd like to explore hitting that path first in
    去拿Map。 它想要先探索这条路径
// forward-only mode and only go for the Map once we notice that we need
    仅向前模式,只有当我们注意到我们需要的时候才去找Map
// lots of look ahead. This doesn't handle reversal as well as two ended
    要向前看。 这并不能像处理两个端点那样处理反转
// search but that's unusual. Besides, for the two ended optimization to
    搜索,但这是不寻常的。 此外,对两端进行了优化
// work on Iterables, we'd need to copy the whole set.
    对于可迭代对象,我们需要复制整个集合。
// In this first iteration, we'll just live with hitting the bad case
    在第一次迭代中,我们将只处理这种糟糕的情况
// (adding everything to a Map) in for every insert/move.
    (添加一切到一个Map中)在每次插入/移动。
// If you change this code, also update reconcileChildrenIterator() which
    如果您更改了这段代码,还需要更新reconcileChildrenIterator() 方法
// uses the same algorithm.
    使用相同的算法。

总结

任性,这个算法不到万得以的情况不能像Vue一样使用双端优化,实在要优化的情况下,还要记得改一下别的方法哦,(我补充一句,改了new文件里面的,也要记得改old文件里面的哦)

忽略所有警告和报错,因为 React JS 代码中有不是 JS 的代码

折叠所有代码

根据 React 文档中给出的场景反复在大脑中运行代码

  • 场景0:单个节点,会运行到 reconcileSingleElement。接下来看多个节点的情况。
  • 场景1:没 key,标签名变了,最终会走到 createFiberFromElement(存疑)
  • 场景2:没 key,标签名没变,但是属性变了,最终走到 updateElement 里的 useFiber
  • 场景3:有 key,key 的顺序没变,最终走到 updateElement
  • 场景4:有 key,key 的顺序变了,updateSlot 返回 null,最终走到 mapRemainingChildren、updateFromMap 和 updateElement(matchedFiber),整个过程较长,效率较低

代码查看要点(忠告):

  • 声明不看(用到再看)
  • if 先不看(但 if else 要看)
  • 函数调用必看

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们