How to check if memory leak occurs when removing a

2019-05-20 07:48发布

问题:

<div id="target">
...

</div>

$('#target').html('') will remove the content,but how to check if the listeners or anything else that holds memory is removed at the same time?

回答1:

Standard JavaScript defines no means to instrument the interpreter's garbage collector, so I don't think this is possible.

However, since removing nodes is not an uncommon operation, I would not worry about browsers leaking memory in this case. Indeed as Piskvor said, the memory is probably not released immediately, but when the garbage collector eventually runs.



回答2:

I am not sure how you can detect a leak within a JavaScript (using JavaScript). but there are tools available to detect the leaks in JavaScript

  • sIEve
  • IEJSLeaksDetector2.0.1.1


回答3:

I'm no expert on this, but since you're using jQuery you should use $('#target').empty(). This detaches all event handlers before removing the child elements. When these are collected is up to the browser, but this ensures that they will get collected when the time comes. You can also use $.remove() to get rid of the selected element and all children.

http://api.jquery.com/empty