I am a little confused how the memory for objects is allocated in
JavaScript. David Flanagan, in "JavaScript : The Definitive Guide,"
states that each property of a class takes up memory space when
instantiated. So space is created for aMethod three times in this
example:
// Example 1
function aMethod() {/*stuff*/};
function AClass() {
/*stuff*/
this.m = aMethod;
};
var a = new AClass();
var b = new AClass();
var c = new AClass();
// End
On the other hand, adding to the property prototype object only takes
up memory space once. Here space is set aside for aMethod once:
// Example 2
function aMethod() {/*stuff*/};
function AClass() {/*stuff*/};
AClass.prototyp e.m = aMethod;
var a = new AClass();
var b = new AClass();
var c = new AClass();
// End
Thus Example 1 should use about three times the amount of memory as
Example 2, according to Flanagan. However, I find myself disagreeing
with the author. All objects are passed by reference in JavaScript.
Since functions are also objects, then in Example 1 space for aMethod
is allocated once and three pointers are created to it. Thus I feel
that Example 1 uses only a little more memory than Example 2. Is this
a mistake in Flanagan's book or a flaw in my own judgment?
--
Jimmy Cerra
P.S. I also feel that Example 1 should run slightly quicker than
Example 2 since the interpreter doesn't have to transverse the
prototype chain in the former example. Some testing with various
browsers confirmed my second suspicion. Unfortunately I don't know
how to test for memory usage in JavaScript, so I could use some advice
with my first suspicion.
[1] Flanagan, David. (2002). javascript: The Definitive Guide, 4th ed.
Sebastopol: O'Reilly & Associates, Inc. Page 120.