React.js如何加速使用虚拟DOM进行渲染 [英] How React.js speeds up rendering with a virtual DOM

查看:216
本文介绍了React.js如何加速使用虚拟DOM进行渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用此( https://news.ycombinator.com/item?id=9155564)article


简短的答案是DOM不慢。添加&删除一个DOM
节点是一些指针交换,并不比在
上设置一个JS对象的属性要多。




DOM是否会瓶颈那些导致重绘的东西?如果是这样,那么React的虚拟DOM渲染的效果应该不会像重绘整个组件一样(在一次浏览器API调用中)?我认为浏览器执行的算法只会尝试重绘diff从一个状态到另一个状态(比如git也许?)。暗示浏览器本身维护一个虚拟DOM。那么,创建一个虚拟DOM有什么意义?

还应该添加一个具有显示样式的元素设置为 none 的属性不会严重影响性能?我会自己分析一下,但是我不知道到哪里去了,因为我最近才开始使用javascript编程。 解决方案

对于SO来说有点宽泛,但作为一般的答案,来自同一篇文章的其他引文也非常相关:


然而,布局是慢... ...
[...]

更糟的是,通过访问某些属性同步触发布局...

[...] >
因为这个原因,很多Angular和JQuery代码都很慢 -
[...]

React并没有帮助加快布局...

虚拟DOM的作用是计算DOM的一种状态与下一个状态之间的差异,最小化DOM中的DOM更新非常聪明的方式



所以:


  • DOM本身就是不慢

  • 但布局很慢

  • 几乎所有的DOM更新都需要布局更新

  • 所以更少的DOM更新速度更快



与其他几个具有虚拟DOM的工具/库相同)。

更多关于虚拟DOM的内容及其优点此处


Quoting this (https://news.ycombinator.com/item?id=9155564) article

The short answer is that the DOM is not slow. Adding & removing a DOM node is a few pointer swaps, not much more than setting a property on the JS object.

Are the DOM bottlenecks only those things that cause a redraw? If so then shouldn't one render from React's virtual DOM amortize to the same performance as redrawing an entire component (in one browser API call of course)? I would think that the algorithms executed by the browser only try and redraw the diff from one state to another (like git maybe?). Implying that the browser maintains a virtual DOM by itself. So then what is the point of having a virtual DOM?

Also should adding an element that has the display style property set to none not be affecting performance badly? I would profile this myself but I do not know where exactly to turn as I started javascript programming only recently.

解决方案

This question may be somewhat broad for SO, but as a general answer, some other quotes from the same article are also very relevant:

However, layout is slow...
[...]
Worse, layout is triggered synchronously by accessing certain properties...
[...]
Because of this, a lot of Angular and JQuery code is stupidly slow
[...]
React doesn't help speed up layout...

What react's virtual DOM does, is calculate differences between one state of the DOM and the next state and minimizes DOM updates in a very smart way.

So:

  • DOM itself is not slow
  • but layout is slow
  • and almost all DOM updates require layout updates
  • so less DOM updates is faster

And the react engine does just that (same as several other tools/ libraries with a virtual DOM).

More info on what virtual DOM is and its advantages e.g. here.

这篇关于React.js如何加速使用虚拟DOM进行渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆