未删除的事件侦听器会消耗多少资源? [英] How much resources does an unremoved event listener consume?

查看:84
本文介绍了未删除的事件侦听器会消耗多少资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个事件监听器函数,该函数正在监听一个事件,该事件在程序的整个生命周期内都不会被再次调用.监听对象将永远不需要进行垃圾收集.

Let's say I've got an event listener function that is listening for an event that will never be called again throughout the lifespan of the program. The listening object will never need to be garbage collected.

这会使用多少内存?
如果可以忽略,我宁愿不删除侦听器,因为使用removeEventListener()语句会使我的代码可读性降低.

How much memory does this use?
If it's negligible, I'd rather not remove the listener because having the removeEventListener() statement makes my code less readable.

推荐答案

这完全取决于侦听器的大小和复杂程度.在许多情况下,对内存的影响可以忽略不计,但是,您要保留在内存中的对象可能会将其他几个对象保留在内存中.如果其中之一是流视频或其他内容,则可能会占用您的内存,处理器和网络.

That depends entirely on how large and complex the listener is. In many cases, the memory impact is negligible, however, the object you're holding in memory may be keeping several other objects in memory. If one of them is a streaming video or something, it may be sucking on your memory, processor, and network.

您还可以在首次添加事件侦听器时将useWeakReferences设置为true.这使得侦听器与事件分配器之间的链接较弱,因此,如果事件分配器在其他任何地方被删除,则后者不会将其保留在内存中. 此处有更多信息.

You can also set useWeakReferences to true when you first add the event listeners. This makes the link between the listener and the event dispatcher weak so that the latter doesn't hold the prior in memory if it's deleted everywhere else. More on that here.

尽管如此,将不再使用的对象留在内存中绝不是一个好主意,也没有理由避免使用removeEventListener().在使代码正常工作之前争取代码的可读性从来都不是一个好主意.如果您担心代码的外观,请将removeEventListener()调用放在名为cleanupUnusedListeners()的方法中.确实,我会说省略它的可读性较差,因为当您寻找内存泄漏的根源时,将很难找到您未放置removeEventListener()的位置.可能不是很漂亮,但这就是事实,杰克.

Still, it's never a good idea to leave objects in memory that are not going to be used again and there's no reason to avoid removeEventListener(). Striving for code readability before making it work correctly is never a good idea. If you're that concerned with the way your code looks, put the removeEventListener() calls inside a method called cleanupUnusedListeners() or something. Indeed, I would say that omitting it is less readable because when you're looking for the source of your memory leak, it will be harder to find the spot where you DIDN'T put a removeEventListener(). It may not be pretty but that's just the way it is, Jack.

这篇关于未删除的事件侦听器会消耗多少资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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