是什么真正使ReactJS达到了它声称的速度?

Sti*_*ing 5 javascript performance reactjs

我正在学习ReactJS并试图了解真正使它比其他框架和库提供的解决方案“更快”和更特别的原因。

我知道以下几点:

  1. Virtual DOM 与其他框架/库中的传统“脏检查”操作相反,React如何运行差异以最少的步骤来确定“更改”并相应地进行响应/重新渲染。
  2. Programmed more declaratively rather than imperatively achieved by "Observable" pattern.

So, the statements above sound all fine and dandy to me conceptually, however, i fail to picture the benefits when i consider real life use-cases and practices:

  1. Considering following with jQuery:

    $("#box").removeClass('red').addClass('blue');

How is it "slower" than doing the same thing the React way? The way i understand it, jQuery will directly grab 1 element from the DOM with the matching id value of "box" and remove and add class as instructed -- all specific to this element within the DOM. (Does it implement "dirty-checking" here to find #box?)

With ReactJS, it would make the same change in its Virtual DOM first (after doing a diff to find #box with minimal # of steps) and re-render the element to the actual DOM. So if anything, it's seems to be adding an extra step of comparing against VDOM.

  1. Observable pattern has been around forever. Why is it the first time it's applied on event-handling operation?.. to do something like:

"Hey, something changed here (event triggered)... so let's see what we're supposed to do about it (run everything bound to the event) and do it"

Any insight, pointers and examples would be greatly appreciated!

Yan*_* Li 7

您可能是对的,在这种情况下,jQuery可能会更快(我尚未测试)。但是请考虑一下,为什么要使用jQuery-如果这样做,它会更快吗?

document.getElementById("MyID").className = document.getElementById("MyID").className.replace(/\bred\b/,'');
document.getElementById("MyID").className = document.getElementById("MyID").className + ' blue';
Run Code Online (Sandbox Code Playgroud)

所以说真的,我们并不是在这里尝试竞争原始速度,否则,您将只使用纯JavaScript编写代码,而且我知道一些公司这样做纯粹是为了在移动设备上更快。

框架的好处是维护和开发速度。用纯javascript编程比jQuery难扩展和维护,同样,用jQuery编程比React难扩展和维护。尽管情况相反,但使用jQuery具有最小功能的应用程序运行起来要快得多(但是在构建mvp之后,维护起来会变得困难得多)

在小型代码库中,jQuery可能比React快,但是当您使用较大的代码库时,您会在jQuery中发现大量重复和冗余的代码,并且它本来就变慢了。但是,React有所不同-首先,React将所有内容隔离到组件中,因此重用变得更加容易;其次,React具有出色的内部引擎,可防止无用的渲染减慢应用程序的运行速度。

所以是的,您是对的,jQuery可以比React更快,但这确实缺少React的要点。就像纯JavaScript可能比jQuery快一样,但这缺少了jQuery的要点。


Bri*_*and 6

React 并不是特别快,它已经足够快了。React 的真正价值在于它提供的声明式 api,它可以让您编写更好的代码。

手动 DOM 操作具有更高的潜在性能,但最终会导致难以维护、难以阅读的代码。这在大型应用程序中是不可接受的,这就是为什么我们转向像 React 这样的工具。

虚拟 DOM 差异是昂贵的。通常,价格不会贵到导致丢帧的程度。更新的 1ms 和 16ms 之间的区别是什么。重要的是你保持在框架内,这就是为什么 React 的性能开销是可以接受的。