Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's AJAX memory leak of response text?

I was debugging my app for memory leaks with the Google Chrome Dev Tools: Heap Snapshots and noticed something strange.

I made an AJAX request to fetch a large blog of JSON and apparently the raw Response Text is sticking around in memory, causing a memory leak in my app.

It seemed unlikely to me that there's a huge memory leak in $.ajax, but I was hoping for an explanation of why this is the case... if I do the same experiment in vanilla JS the leak isn't shown.

1) Pure JavaScript XHR

  • source: http://jsfiddle.net/HZmT5/2/ (using XMLHttpRequest)
  • output: http://fiddle.jshell.net/HZmT5/2/show/light/
  • No leak shown

2) Using $.getJSON

  • source: http://jsfiddle.net/JmA8v/1/ (using $.getJSON)
  • output: http://fiddle.jshell.net/JmA8v/1/show/light/ (leak shown)
  • Leak shown, see screenshot:

Screenshot: the entire HTTP Response of the XHR request stuck around in memory. "Snapshot 1" is before the button is pressed. "Snapshot 2" is after. Notice the screenshot below and it's the Comparison of the before/after of the Heap.

The same behavior wasn't reproduced in the pure-JS version.

enter image description here

(Of course the HTMLDivElement will still remain in the heap since it's in the DOM, but it seems unnecessary that the full JSON object remains in the heap)

like image 829
philfreo Avatar asked May 09 '14 19:05

philfreo


1 Answers

This video demonstrates that actually there is no memory leak. jQuery fetches the new version of the string and v8 releases the old one. The reason of that behavior is the fact that V8 engine uses many different tricks for optimization and may keep a reference to an object inside its internal structures and generated code.

The blue bars in the video are the moments in time when profiler found new objects/strings in the v8 heap. The bars become grey when v8 collects these objects as a garbage.

like image 132
loislo Avatar answered Sep 29 '22 19:09

loislo