React.js应用程序占用了大量内存(几乎是原始实现的两倍) [英] React.js app using up a lot of memory ( almost double the original implementation )

查看:1013
本文介绍了React.js应用程序占用了大量内存(几乎是原始实现的两倍)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近将一个沉重的页面移植到了React.我保持html几乎相同.主要区别在于,以前,服务器呈现的html是直接提供给浏览器的,现在,react重写通过服务器端API提取json并使用React来管理DOM.

I recently ported a heavy page to React. I've kept the html almost identical. The main difference being that, earlier, the server rendered html was directly given to the browser and now, the react rewrite pulls json via a server side API and uses React to manage the DOM.

我已经看到较早实现的堆快照高达 55 MB .对于相同的数据,React.js实现的堆快照大约为 100+ MB (几乎是两倍)

I've seen heap snapshots for the earlier implementation going up to 55 MBs. For the same data, the heap snapshot for the React.js implementation comes to around 100+ MBs(almost double)

我知道保存在内存中的json数据将有助于增加所消耗的内存.但是,当我检查堆快照时,发现大约60%的保留大小是由于某些对象的保留路径包含 deleteAllListeners> ....> unmountComponentAtNode 所致.我试图了解这对于减少使用的内存意味着什么.

I understand that the json data held in memory will contribute to some increase in the memory consumed. But, when I examined the heap snapshot, I see that around 60% of the retained size is due to some objects whose retaining path contain deleteAllListeners > .... > unmountComponentAtNode . I am trying to understand what that means in terms of reducing the memory used.

此外,React添加到DOM的"data-reactid" 属性是否会导致内存消耗的增加不可忽略?

Also, could the "data-reactid" attributes added by React to the DOM contribute to a non-negligible increase in memory consumption ?

此问题包含一些可能会有所帮助的详细信息.

This question has some more details that might help.

推荐答案

React使用的是虚拟DOM.基本上,除了现有的浏览器DOM树之外,它还在内存中构造替代的DOM树,但是要执行有效的更新,它必须将最后显示的虚拟DOM树保留在内存中,以便它可以快速有效地更新浏览器DOM树.

React is using something called Virtual DOM. Basically it constructs alternative DOM tree in memory, in addition to the existing browser DOM tree, but to perform efficient updates it has to keep last displayed Virtual DOM tree in memory, so it can generate fast and efficient updates to the browser DOM tree.

根据第二个问题的详细信息,我了解到您可以无限滚动,当用户向下滚动页面时,基本上可以在其中添加新组件(而不删除新组件).因此,这应该是增加内存使用量的根源(因为与以前的解决方案相比,现在您的内存中有数据+虚拟dom)

From details of second question, I understand that you have an infinite scroll, where you basically add new components (without removing new ones) when user scrolls down the page. So this should be the source of increased memory usage (since now you have data + virtual dom in memory, compared to the previous solution)

解决方法是仅呈现用户实际可见的组件,您可以尝试使用反应列表,或为此实现自己的组件.

The way it fix it is to render only components which are actually visible to the user, you can try to use react-list, or implement your own component for this.

这篇关于React.js应用程序占用了大量内存(几乎是原始实现的两倍)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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