Sam
Sam

Reputation: 11

Javascript: memory leak with loop?

I've got a simple loop that creates and destroys (hopefully) empty objects: http://jsfiddle.net/TgWze/

function Test()
{
}

function generate()
{
    for(var i = 0; 1000 > i; ++i)
    {
        var view = new Test();

        delete view;
    }
}

The memory profile in Chrome/Safari shows memory-leak like behavior if I keep clicking the link: http://cl.ly/BnCV

Am I missing something?

Upvotes: 1

Views: 1106

Answers (3)

Vlad A. Ionescu
Vlad A. Ionescu

Reputation: 2788

That code does not leak.

To convince yourself you can take snapshots of the memory and compare before and after. Have a look at this guide that I wrote, for more details: http://www.vladalexandruionescu.com/2012/08/javascript-memory-leaks.html.

Upvotes: 0

Joe
Joe

Reputation: 82594

It's managed memory. So it will collect the deleted object at some point when the garbage collector runs. You deleting the objects actually doesn't do anything. However since, view is never reference, it should be collected easily.

Upvotes: 3

SLaks
SLaks

Reputation: 887405

That looks like normal GC behavior. Once there are too many objects, the GC cleans them up.

It would only be a memory leak if the troughs after each peak (just after the GC runs) get successively higher, indicating that the GC didn't catch everything.

Upvotes: 3

Related Questions