I recently came across a bit of code at work that has me stumped what the original coder was thinking. The gist of the code was this:
function func1(array1) {
var returnVal = false;
try
{
// Do something. (No effect on array1)
}
catch (e)
{
CallDebugger(e.description);
}
finally
{
// Clean up the memory?
array1 = null;
}
return returnVal;
}
function func2() {
var arr = [1,2,3]
var ret = func1(arr)
}
My question is: what exactly does setting array1 to null at the end of func1 do? Does it change arr to null in func2? Or does changing array1 to null create a new reference to a null variable? Something else?
Does this have any potential benefits as far as memory leak is concerned?
It seems quite unreasonable to do array1 = null
in that case.
What exactly does setting array1 to null at the end of func1 do? Does it change arr to null in func2?
Basically, array1
is a copy of reference to arr
in func2
. So that assignment will change variable only in func1
scope and nowhere else, so arr
in func2
stays unchanged. And doing so in finally statement at the end of a function, is not useful, because func1
ends right after finnaly statement and reference to array1
will be garbage collected and no one will ever know that it was set to null
(expect if it was in a closure before finally, but you say it's not).
Or does changing array1 to null create a new reference to a null variable?
It just sets array1
's value to null, and as I said before: arr
in func2
won't be changed in that case.