Question

Does any one know why memory consumption stays constant here ?

var count = 0;
$(init);

function init(){
    var node =  document.querySelector('.logs');

    function check(){
        var uArr = new Uint16Array(100);
        log(node, uArr.length);
        setTimeout(check,100);
    }   
    setTimeout(check,100);
}      


function log(node, text){
    if( count % 30  == 0 ){
        node.innerHTML = '';
    }
    var child = document.createElement('div');
    child.innerText = 'count ' + (count++) + " arr len "  + text;
    node.appendChild(child);
}

http://jsfiddle.net/V99Eb/11/

Reason why it should linearly increase memory allocation is: the 'check' method calls itself inside it's definition, so the closure variables will be available to the inside check method execution, which then again creates an execution context for the test function and so on.

Also, in every execution, we create a memory block of Uint16Array, which I believe is allocated in the heap, and should never get de-allocated since it is reachable from the closure.

Memory Profile: enter image description here

Looking at the memory timeline, it does not seem to increase memory allocation as the time increases. Is this the expected behavior ?

Was it helpful?

Solution

uArr is just a local variable that is allocated, used, and then garbage collected after check() exits. And there is no closure inside check(). setTimeout() is invoked (but not defined) by check().

This page on Closures may be helpful.

While it is true that if there are N calls to check(), there would have been N closures created (as well as N copies of node), setTimeout() will release its reference to check() after it calls it. Therefore, there is no leak there either.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top