philfreo
philfreo

Reputation: 43864

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

2) Using $.getJSON

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)

Upvotes: 7

Views: 2142

Answers (2)

guest271314
guest271314

Reputation: 1

Perhaps missing something, yet jsfiddles at original post appear return same results ?

Also, would

$.ajaxSetup({cache : false})

affect results ?

To delete browser cache at chromium/chrome browser, at Terminal (*nix) try

find ~/.cache/chromium/Default/Cache -type f -exec rm -f {} \;

find ~/.cache/chromium/Default/Media\ Cache -type f -exec rm -f {} \;

replacingchromium with chrome if needed. Alternatively, navigate to the

chromium or chrome folder at device, navigate to each Default and Media Cache folders within, and delete contents.

Upvotes: 0

loislo
loislo

Reputation: 14129

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.

Upvotes: 6

Related Questions