1

I'm not a JavaScript professional, so my question might seem ridiculous. Suppose i have the following HTML block:

<div>
     <script type="text/javascript">
         var variable_2  = new SomeObject();
     </script>
</div>

This clearly allocates memory on the heap for the SomeObject instance and variable_2 resides in the global context.

My question is: If I have generated the previous HTML block again by using AJAX, i will then have variable_2 reference a newly allocated instance of SomeObject in the global context, right? But then, what happens to the previously allocated instance, is it garbage collected or this is a memory leak?

In addition, if you may include a reference to a book or article that describes the best practices of JavaScript memory management?

hiddenUser
  • 674
  • 1
  • 7
  • 19

2 Answers2

0

Take a look at this post or this post for more info on JS garbage collectors. Note however that the exact behaviour is probably subtly different between JS engines. You might want to post a question on eg. the V8 forum for a detailed technical explanation.

In my opinion, I would certainly avoid doing what you describe because its bad practice. In reality I would be surprised if it caused a memory leak in a decent JS engine though (either the.

UpTheCreek
  • 31,444
  • 34
  • 152
  • 221
0

When an object becomes unreachable it will be garbage collected. Older versions of Internet explorer (versions 6 and 7) had an issue where objects that reference each other but became unreachable would not be garbage collected, thus causing a memory leak. However, this is irrelevant to your example. In your example, once there are no more references to the first object (i.e., when you reassign the variable) the object becomes unreachable and will be garbage collected.

You can read about JavaScript memory management at https://developer.mozilla.org/en-US/docs/JavaScript/Memory_Management

orb
  • 1,263
  • 1
  • 10
  • 16