Reputation: 4769
Is it possible freeing the browser memory from JavaScript objects?
I am designing the asynchronous navigation process of a web app, in which page parts are loaded through AJAX requests together with their necessary components (CSS, JS, images etc): I guess that without a proper scripting, a long usage of the app would load many different objects causing a brutal memory growth.
As I could imagine, the removal of a script tag from the DOM only removes the DOM node, not the objects and functions it defines, which remains loaded into the browser memory. (A similar test: Should a "script" tag be allowed to remove itself?).
I also tried to test the browser behaviour while setting a variable as a big string and then overwriting it:
<html>
<head>
<title>JS memory test</title>
<script type="text/javascript">
function allocate() {
window.x = '';
var s = 'abcdefghijklmnopqrstuvwxyz0123456789-';
for (var i = 0; i < 1000000; ++i) {
window.x += 'hello' + i + s;
}
alert('allocated');
}
function free() {
window.x = '';
alert('freed');
}
</script>
</head>
<body>
<input type="button" value="Allocate" onclick="javascript:allocate();" />
<input type="button" value="Free" onclick="javascript:free();" />
</body>
</html>
Data from the Chrome task manager:
page weight when loaded: 5736 KB page weight after having set the variable: 81720 KB page weight after having the variable reset: 81740 KB
It strikes me since I thought the JS garbage collector throws away the old variable value, since it is overwritten from the new assigned value.
Firefox has not a single-task-tab management, so there's not a similar process monitor like in Chrome, but the global memory usage seems that it behaves almost like Chrome.
Is there some wrong assumption?
Can somebody provide suggestions about effective programming practices or useful resources to read?
Thanks a lot.
Upvotes: 1
Views: 2663
Reputation: 147413
You have no direct access to memory management features. The best you can do is remove references to objects so that they are available for garbage collection, which will run from time to time as the browser sees fit.
From time to time certain browsers exhibit memory leaks, there are strategies to reduce them but usually for specific cases (e.g. the infamous IE circular reference leak, which has been fixed, even in updated versions of IE 6, as far as I know).
It's probably not worth worrying about unless you find you have issues. Deal with it then.
Upvotes: 2