On Tue, Jun 10, 2014 at 9:58 PM, Ilya Kantor <[email protected]> wrote:

> Hi,
>
> When I create many objects new Machine like this
> ```
> function Machine(power) {
>   var enabled = false;
>
>   this.enable = function() {
>     enabled = true;
>   };
>   this.disable = function() {
>     enabled = false;
>   };
> }
>
> var machines = []
> for(var i=0; i<10000; i++) machines.push(new Machine)
> ```
>
> ...I see in Chrome Heap Profile that every object has 36 bytes for
> function enable/disable.
> That is so even if the function code is actually longer.
>
> Do I get it right that V8 actually creates these functions only ONE time
> and uses it for all machines?
>

Depends on what you mean by "create these functions". Unoptimized generated
code is shared among closures. But they *are* separate objects, e.g. you
can do:
machines[0].enable.foo = "bar";
and after that machines[1].enable.foo will still not exist, because each
machine's "enable" function is a separate object.

In fact, they will even be optimized individually. E.g. if you call
machines[0].enable() a lot, it might get optimized, while machines[1].enable
is still unoptimized. Not that it matters for such a trivial example :-),
but for a larger, "real" case you might actually care. The pattern Stefan
suggested earlier would solve this. Of course there are many other ways to
get the same effect, e.g.:

var Machine;
(function() {
  function EnableMachine() { this.enabled = true; }
  Machine = function() {
    this.enabled = false;
    this.enable = EnableMachine;
  }
})();

I think there are some things we can do in the future to handle your
original code better and share some more optimized code (which we already
do in some cases), but there will always be some overhead/inefficiency when
many closures are used, which cannot be optimized away because doing so
would lead to observably different behavior, which would be wrong. In
general, I would recommend to use closures only when you really need to
have separate objects. (Or when you don't care about memory consumption nor
performance.)

Sharing code between closures is unrelated to hidden classes.

-- 
-- 
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to