There is a dynamic website of 10 pages (it works using the history API ). When you go to the first page, a .js file is dynamically loaded that contains an object that performs certain actions on the page. It is the same for other pages, when you go to any of the 10 pages, your object is loaded with its own methods and properties.

So, it is necessary that when switching to other pages the object is permanently deleted and not hung in memory.

How to delete an object? Like this: obj = null; or obj = {};

Or is there another way, more correct?

If you delete objects using the methods I specified, after about what time will the garbage collector finally delete the objects themselves?

And another question:

If instead of an object there is a function, then how is it properly removed? So: func = null;

I would like to rely on your experience in developing dynamic applications. How would you implement the mechanism of this application?

  • one
    I am afraid that this question simply does not exist a definite answer. This is done for users with different sets of hardware and software, and the collector "should not". - D-side

2 answers 2

How to delete an object? Like this: obj = null; or obj = {};

In both cases, the obj link will remain, which will be shown on something. You can completely remove it as follows:

 delete obj; 

The object that was under the link will be deleted only when it is reached by the garbage collector, whose behavior depends, for example, on the browser. To speed up this process, as far as I know, is generally impossible.

Here is a good article (in English) about memory optimization in javascript.

  • if you keep dynamic data in a worker, you can speed it up :) - zb '
  • one
    I recently checked it out in chrome - I’m freezing the memory of the listener that is freed when the object is removed. - zb '

I don’t know how legitimate it is ... If an object is loaded from a file into a <script> and there is a link to it, then removeChild() seems to remove the object without a trace. Let the gurus fail the theoretical base.

In my case, objects with the same call function were loaded via xmlhttp into <head><script>...</script></head> . If in the same script to load new content through innerHTML , the old object is recalled from memory, despite obj = null , obj = {}; and even delete Object . And if you delete the script (removeChild) and appendCild(createElement('script')) new appendCild(createElement('script')) to the head, the new appendCild(createElement('script')) is called, despite the fact that its name is the same as the previous one.

Hence the conclusion - the object is removed in this way with all __proto__ and other chains.