Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do nested function declarations create a new object each call?

Tags:

javascript

v8

Does the anonymous function in Foo get re-created in memory each time Foo() gets called?

function Foo(product)
{
    return function(n) {
        return n * product;
    }
}

I'm more or less interested in V8's implementation in particular, since I'm not seeing anything in regards to that in the spec (unless I'm missing something, which I probably am).

I'm kind of confused on the memory management going on since the use of product is specific to the closure that is returned; however, that doesn't necessarily say the inner function has to be re-created along with a closure instance (in theory), since you can still .bind() without losing closure values.

like image 918
Qix - MONICA WAS MISTREATED Avatar asked May 24 '14 01:05

Qix - MONICA WAS MISTREATED


3 Answers

As far as I know a new function object gets re-created everytime, but the function's code (body) is normally getting reused. I do not know under what circumstances it wouldn't be however.

https://groups.google.com/forum/#!topic/v8-users/BbvL5qFG_uc

like image 90
plalx Avatar answered Oct 24 '22 06:10

plalx


This code snippet shows that you're getting a new Function object each time:

function Foo(product)
{
    return function(n) {
        return n * product;
    }
}

var a = Foo(2);
var b = Foo(2);

alert(a === b);    // alerts false

Demo: http://jsfiddle.net/wc5Lv/


There are probably interpreter optimizations that can internally reuse the parsed function, but from the pure javascript point of view, a new Function is created each time.

like image 36
jfriend00 Avatar answered Oct 24 '22 07:10

jfriend00


Yes. The ECMAScript specification, 5ed, requires that each evaluation of a function expression or function declaration generates a new function object. If you read the cases of http://es5.github.io/#x13 they all contain the phrase "a new Function object"

That just means that there is a new Function object, but most of the internal content of that function object can be shared between instances, including the code generated for the function body. The new object only needs to hold the value of the product variable and a reference to the shared function implementation.

like image 2
lrn Avatar answered Oct 24 '22 05:10

lrn