Does the variable delete before closing the tab / window, freeing up memory?

I support JavaScript code where a function that does some heavy processing to generate arrays stores the results in a cache variable inside the function itself. It is implemented as follows:

function heavyProcessingStuff(x) { if(heavyProcessingStuff.cache == undefined) heavyProcessingStuff.cache = []; if(heavyProcessingStuff.cache[x] != undefined) { return heavyProcessingStuff.cache[x] } else { return heavyProcessingStuff.cache[x] = x + 1 } } 

It is strange that there is a function that executes when a page is unloaded, which manually deletes each property of the cache variable, for example:

 for (n in heavyProcessingStuff.cache) { delete heavyProcessingStuff.cache[n] } 

I am confused why this was implemented in this way.
Is this specific to some strange corner case? Do you have any motivation? No need / should browser garbage collect everything when the page closes?

+5
source share
3 answers

Javascript uses garbage collection, and it's better not to free memory explicitly. A good reading on this subject can be found in the section "De-references to misconceptions" in the article "Writing Fast, Effective for Working with Memory" .

Quote from the article:

Cannot force garbage collection in JavaScript. You would not want to do this, because the garbage collection process is controlled by runtime, and it is usually best known when things should be cleaned.

+3
source

Not seeing the full context, there is another possibility:

Earlier versions of IE (I know IE6 was susceptible) used a simple reference counting system to collect garbage. The problem is that the DOM and JavaScript kept separate reference standards.

This allowed us to create a situation where the DOM (via the expando property) can contain a link to JavaScript, and JavaScript to a DOM link.

These circular links would create a memory leak that continued beyond the page, and the memory was freed only when the page window was closed.

It was common to use the unload event to free memory and free any event handlers to avoid this.

+1
source

In Chrome and Internet Explorer (or in any browser that implements the process model per tab) you are right, there is absolutely no value. In fact, it spends CPU time trying and deleting, because often, when the tab is closed, the process is killed, freeing up all non-shared resources.

For browsers that are one process (Firefox still, although progress is already being made to change this), perhaps this can make the garbage collector work faster if the number of links is reduced to 0, but it probably also makes no sense. Other than very old ( IE6, for example ) browsers, every modern garbage collector is likely to shift everything in the next pass, regardless of whether you explicitly delete links or not.

-1
source

Source: https://habr.com/ru/post/1200879/


All Articles