在阅读了有关 ReactJS 和 Angular(不是 AngularJS)的变更检测和渲染阶段的文档和几篇文章后,我想到了一个问题,稍后我将尝试解释这个问题。
正如您可能已经在 React 的文档(here 和 here)中读到的那样,存在一个名为“Reconciliation”的概念(如果您愿意的话),它基本上指的是“ Diffing Algorithm”和在调用“render”方法并创建 React 元素树后执行的过程,DOM 应该更新相应地...正如在他们的文档中所说,React 实现了一种启发式 O(n) 算法,该算法将新版本的虚拟 DOM (VDOM) 与之前的版本进行比较,以便有效地仅更新那些真正具有的 View 部分改变了。
但是谈论 Angular,正如我在一些文章中读到的那样 here , here和 here ,另一方面,似乎 Angular 只查看它从模板派生的“绑定(bind)”:
When the compiler analyzes the template, it identifies properties of a component that are associated with DOM elements. For each such association, the compiler creates a binding in the form of instructions. A binding is the core part of change detection in Angular.
然后:
Once bindings are created, Angular no longer works with the template. The change detection mechanism executes instructions that process bindings. The job of these instructions is to check if the value of an expression with a component property has changed and perform DOM updates if necessary.
总结一下:
Processing bindings that perform dirty checks and update the relevant parts of the DOM are the core operations of change detection in Angular.
(来自第三个链接)
所以我的问题是,当 Angular 仅在“绑定(bind)”而不是整个新生成的模板/VDOM 上运行变更检测时,我们是否可以说 Angular 实现了与 React 类似的性能提升,从而消除了需要优化的差异算法吗?
或者 Angular 的变化检测中是否还有其他一些实现这种效率的点?
最佳答案
can we say that Angular achieves a similar performance boost... thus eliminating the need for an optimized diffing algorithm
是
React 中实际上没有进行太多优化。它只是比较返回的子元素的类型并丢弃树。与 key 的比较更加复杂。我会说 Angular 运行变更检测的速度更快,因为所有的 child 在编译时都是已知的,但 React 更灵活,因为你每次都可以返回一个全新的 child 。在 Angular 中,您需要了解一大堆概念才能动态更改或删除子项。在 React 中,这只是从 render
方法返回不同子项的问题。
关于Angular:它是否与 ReactJS 的 "Reconciliation"等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53087567/