Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can bind function in Javascript cause a memory leak?

I think this code might be causing a memory leak:

function foo(arr, value){
    arr.push(value);
    console.log(arr);
}
var bar = foo.bind(null, []);
bar('first call');//output: ['first call']

//The next thing that confused me is happened, 
//'first call' has been hold in 'arr' after bar('first call') execute:

bar('second call');//output: ['first call', 'second call'];

I was wondering why GC is not a collection of the reference of the first function's parameter after the first function has been executed?

I would have thought that every time the bar function is executed, the formal parameter arr should be initialize to [].

Also what is the difference between arr/[] and below the variable arr2?

var arr2 = [];
function foo2(value){
    arr2.push(value);
    console.log(arr2);
}
var bar2 = foo2.bind(null);
bar2('first call 2');
bar2('second call 2');

Thanks in advance!

like image 425
Xheldon Cao Avatar asked Oct 22 '25 04:10

Xheldon Cao


1 Answers

You're binding the first argument not to the concept of a new array, but rather to a specific object which you create and which is initialized to the new array. More precisely, variables in JavaScript are labels/pointers for objects. Many labels can refer to the same object, and when the underlying object is modified, each label "sees the change". The exception is primitive types, and types which are otherwise immutable (string, date etc.), for which in-place modification is not allowed.

The following code would be equivalent:

var baz = []; // or baz = new Array();
var bar = foo.bind(null, baz); // bind first argument to object pointed to by baz.
bar('first call'); // operates on baz, making it ['first call']
bar('second call'); // operates on baz, making it ['first call', 'second call']
baz.push('x'); // ['first call', 'second call', 'x'];

Also, in response to your question, this is standard behaviour. It's more or less the same in all other programming languages with similar semantics (Python, Ruby, C#, Java etc.). So it's a memory leak only when foo2 lives on forever, yet you wanted it to live just for a short while.

like image 134
Horia Coman Avatar answered Oct 23 '25 19:10

Horia Coman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!