javascript - Enclosure Memory Copies -


function myclass() {   //lots , lots of vars , code here.     this.bar = function()    {      //do numerous enclosed myclass vars    }     this.foo = function()    {       alert('hello'); //don't enclosed variables.    } } 

each instance of myclass gets own copy of bar , foo, why prototyped methods use less memory. however, know more memory use of inner methods.

it seems obvious me (1) below must true. agree?

  1. not distinct myclass instances have own distinct copies of bar, must have own distinct copies of myclass enclosure. (or else how bar method keep myclass variables straight on per instance basis?)

now (2) question i'm after.

  1. since inner foo method doesn't use in myclass enclosure natural qustion is: javascript smart enough not keep myclass enclosure in memory use of foo?

this depend entirely on implementation not language. naive implementations keep far more around others. answer true e.g. v8 (chrome's js engine) may not true spidermonkey (firefox's) or jscript (ie) etc...

in experience (this how ghc handles closures), actual code of functions (inner or outer) exists once, "environment" mapping variables values must kept around closure (bar), no, wouldn't expect js implementation keep around more 1 copy of myclass, keep around copy of environment @ least this.bar, sensible implementations might realize no environment needed foo not closure, , not need keep copy of environment call myclass not rely on behaviour.

especially since behavior of js's eval function evaluates string in same lexical environemnt eval call, quite js implementations always keep lexical environment around.


Comments

Popular posts from this blog

php - Replacing tags in braces, even nested tags, with regex -