[Vuejs]-Trying to understand what is actually memory leak

0👍

JavaScript does not have memory leaks (in the traditional sense) because it has automatic garbage collection. The JS interpreter records a reference count for every object (including numbers, strings, etc.). When the reference count hits 0, the object will be deleted (usually using a ‘mark-and-sweep’ algorithm).

So, in your example, exampleData.name is actually a reference to some object (number, string, JS object, etc.), and when you enter exampleData.name = {}, two things happen (let’s assume exampleData.name was originally equal to the string “oldname”):

  1. ‘{}’ creates a new object with a single reference count (exampleData.name now points to it)
  2. The string object “oldname” now has a reference count of 0, because its only reference, exampleData.name, not points to something else. Now, the next time the garbage collector runs, exampleData.name will be deleted.

Having said that, it is possible to unintentionally waste memory (though not a memory leak in the traditional sense) in certain JavaScript scenarios, like the following closure:

function wastefulFunc(){
    var giantObj = {};
    ///fill giantObj up with thousands of entries
    function closureFunc(){}
    return closureFunc;
}
var waste = wastefulFunc();

Even though it doesn’t look like it, giantObj will be kept around for as long as the ‘waste’ var exists, because the scope created by closureFunc sets the reference count of giantObj to 1.

As for a ‘true’ memory leak, consider a language like C++, which doesn’t have automatic garbage collection:

void leakFunc(){ Foo* f = new Foo; }

The code above creates a pointer, f, which points to an explicitly allocated Foo object. As soon as the function finishes, however, the variable f will be destroyed, but we have no way of referencing the memory it pointed to. Since C++ does not have automatic garbage collection, the allocated memory that f pointed to will forever be marked as allocated, and we CANNOT get free it, because we have lost any way of referencing it! Therefore, the memory has ‘leaked’ out of the pool of memory available to our program.

Leave a comment