views:

51

answers:

2

This seems rather obvious to me, but I just wanted to make sure. In terms of memory used when the foo function is stored, would it better to do this:

function foo(){
    var hey = {};
    hey.a = 1;
    hey.b = 1;
    alert('done');
}

or

function foo(){
    var hey = getHey();
    alert('done');
}
function getHey(){
    var hey = {};
    hey.a = 1;
    hey.b = 1;
    return hey;
}

Since getHey() is just going to be a reference to the actual function, I'm not sure whether it stores foo as is, or with an embedded getHey.

A: 

logically the function will be stored in memory while the parent scope lives. and that reference does take a bit of memory but the real danger is usually the overhead when calling function in a loop, just having a single function call inside a large for-loop could add a lot of processing time.

tutuDajuju
So, if I stored a couple thousand instances of `foo` in a hash, the hash would take up the same amount of memory for both cases?
Azmisov
the program itself in memory would probably be slightly bigger but the variables declared should take the same. usually this is not an issue though as i described above, the time it takes to read that function (call overhead) will amount to huge perf. loss.
tutuDajuju
A: 

They're separate functions. What'd probably save some space however is:

function foo() {
  var hey = { a: 1, b: 1 };
}
Pointy