473,657 Members | 2,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory requirements for an object's methods

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.
Jul 23 '05 #1
9 1590


Jimmy Cerra wrote:
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();
In this case there are three objects a, b, c each having a property named m.
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();
In this case only the AClass.prototyp e object has a property named m.
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.


I don't know why you name "objects are passed by reference" to reason
about the memory use as there are no functions with parameters above
meaning there is no passing of parameters at all.
As for the memory usage all you can say from the ECMAScript formal model
is that the first example has a prototype object with one property named
m independent of the number of objects created with new AClass() while
the second has a property named m for each object created with new
AClass(). How that relates to the memory consumption of a implementation
in C or Java depends on the implementation.

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 23 '05 #2
ji*******@hotma il.com (Jimmy Cerra) writes:
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.
True. It takes up space in the object's mapping from property name to
value. In some browsers that is implemented as a hash map, in others,
it is merely added to a list that is searched linearly, but it does
take up a little space (but not much).
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

No. The aMethod function is only created once. However, each object
created from the AClass constructor function will have a reference
to it in its property mapping.
On the other hand, adding to the property prototype object only takes
up memory space once. Here space is set aside for aMethod once: AClass.prototyp e.m = aMethod;
Yes, here the property is added to the prototype object, which is shared
by all three instances.
Thus Example 1 should use about three times the amount of memory as
Example 2, according to Flanagan.
No. You are only having duplicate references, not duplicate objects.
And there are *many* other objects that uses memory as well. Each
instance of aClass uses memory, which you should take into account
too.
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?
Read literally, it would be a mistake in Flanagan's book. However, how
does he suggest that you create properties. If he suggests:

function AClass() {
this.m = function aMethod(){};
}

*then* a new instance of aMethod is created for each instance of AClass.
Still, even if you created a million instances, then this will only take
about twice the memory of the prototype version, since you still create
a million AClass instances.
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.
Yes, that is to be expected.
Unfortunately I don't know how to test for memory usage in
JavaScript, so I could use some advice with my first suspicion.


I'd take a fresh browser and create a *lot* of instances (and save a
reference to them, so they won't be garbage collected early) and then
check the difference in the operating system's reported size for the
browser.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #3
Martin Honnen,
// Example 1
... In this case there are three objects a, b, c each having a property named m.


I agree.
// Example 2
...

In this case only the AClass.prototyp e object has a property named m.


I agree.
I don't know why you name "objects are passed by reference" to reason
about the memory use as there are no functions with parameters above
meaning there is no passing of parameters at all.
I'm sorry: I didn't write what I meant. When I visualize JavaScript code in
my head, I see operators and statements as functions. I should have wrote,
"you can only use objects by reference." In example:

var a = new Object();
var b = a;
b.name = "Alf";
window.alert(a. name); // alerts "Alf";
How that relates to the memory consumption of a implementation in C or Java
depends on the implementation.


True, but it does specify when a function is parsed into a separate object. Right?

--
Jimmy Cerra
Jul 23 '05 #4
Lasse Reichstein Nielsen,

// Example 1
... No.
...


That's what I thought. I was referring to what David Flanagan was
implying.

Thus Example 1 should use about three times the amount of memory as
Example 2, according to Flanagan.

No.
...


That's what I thought, hence I appended that with "according to
Flanagan." :-)

Read literally, it would be a mistake in Flanagan's book.
He wrote a more complicated version of what I showed. FYI, I appended
the exact text and example that confused me. My issue is with "we've
more than tripled the memory requirements of each Rectangle object."
The excerpt is referenced from:

Flanagan, David. (2002). javascript: The Definitive Guide, 4th ed.
Sebastopol: O'Reilly & Associates, Inc. Pages 119-120.

function AClass() {
this.m = function aMethod(){};
}

*then* a new instance of aMethod is created for each instance of AClass.
Still, even if you created a million instances, then this will only take
about twice the memory of the prototype version, since you still create
a million AClass instances.


I disagreed at first, but some testing proved me wrong! Thanks for
the
insight.

Unfortunately I don't know how to test for memory usage in
JavaScript, so I could use some advice with my first suspicion.

I'd take a fresh browser and create a *lot* of instances (and save a
reference to them, so they won't be garbage collected early) and then
check the difference in the operating system's reported size for the
browser.


I have no idea how to do that reliably.

--
Jimmy Cerra
--
Example 8-3. Defining methods in a constructor

// First, define some functions that will be used as methods.
function Rectangle_area( ) { return this.width * this.height; }
function Rectangle_perim eter() { return 2*this.width + 2*this.height;
}
function Rectangle_set_s ize(w,h) { this.width = w; this.height = h; }
function Rectangle_enlar ge() { this.width *= 2; this.height *= 2; }
function Rectangle_shrin k() { this.width /= 2; this.height /= 2; }

// Then define a constructor method for our Rectangle objects.
// The constructor initializes properties and also assigns methods.
function Rectangle(w, h)
{
// Initialize object properties.
this.width = w;
this.height = h;

// Define methods for the object.
this.area = Rectangle_area;
this.perimeter = Rectangle_perim eter;
this.set_size = Rectangle_set_s ize;
this.enlarge = Rectangle_enlar ge;
this.shrink = Rectangle_shrin k;
}
// Now, when we create a rectangle, we can immediately invoke methods
on it:
var r = new Rectangle(2,2);
var a = r.area();
r.enlarge();
var p = r.perimeter();

The technique shown in Example 8-3 also has a shortcomming. In this
example, the Rectangle() constructor sets seven properties of each and
every Rectangle object it initializes, even though five of those
properties have constant values that are the same for every rectangle.
Each property takes up memory space; by adding methods to our
Rectangle class, we've more than tripled the memory requirements of
each Rectangle object. Fortunately, Javascript has a solution to this
problem: it allows an object to inherit properties from a prototype
obejct. The next section describes this technique in detail.
--
Jul 23 '05 #5
ji*******@hotma il.com (Jimmy Cerra) writes:

[quoting Flanagan]
function Rectangle(w, h)
{
// Initialize object properties.
this.width = w;
this.height = h;

// Define methods for the object.
this.area = Rectangle_area;
this.perimeter = Rectangle_perim eter;
this.set_size = Rectangle_set_s ize;
this.enlarge = Rectangle_enlar ge;
this.shrink = Rectangle_shrin k;
} The technique shown in Example 8-3 also has a shortcomming. In this
example, the Rectangle() constructor sets seven properties of each and
every Rectangle object it initializes, even though five of those
properties have constant values that are the same for every rectangle.
Each property takes up memory space; by adding methods to our
Rectangle class, we've more than tripled the memory requirements of
each Rectangle object.


Here he is comparing the number of properties, going from 2 to 7,
which is more than three times as many properties. Since each property
probably uses the same amount memory, this more than triples the memory
requirements of *the properties* of each Rectangle object.

This is *not* counting the memory used for the object itself, which
should count for something. My guess would be that the memory for the
object itself is significant when dealing with as few properties as
this. Then again, if you are planning on making a million rectangles,
then every bit counts, and if you have *many* properties, the problem
scales as well.

I try to use methods on the prototype as much as possible for this
exact reason.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #6


Lasse,

I think I understand. I just want to make sure... In Flanagan's
example, there are 2 properties representing some data - probably
numbers so I'll assume that's what they are. that's what they are.
There are also 5 more properties that are references to functions, and
these references never change.

To simplify everything, I'll assume that each function takes up the same
space, which is also more than the references and the numbers. If I was
implementing a JavaScript interpreter, then each reference would
probably be internally represented by a 32-bit reference, and each
number could be represented by a 64-bit data type (by the maximum size
of a number in JavaScript). I'll assume that the functions take up 64
bytes each.

So we have:

64 bytes for Rectangle_area
64 bytes for Rectangle_perim eter
64 bytes for Rectangle_set_s ize
64 bytes for Rectangle_enlar ge
64 bytes for Rectangle_shrin k

8 bytes for a number type per obejct
8 bytes for a number type per obejct

4 bytes for a reference to Rectangle_area per object
4 bytes for a reference to Rectangle_perim eter per object
4 bytes for a reference to Rectangle_set_s ize per object
4 bytes for a reference to Rectangle_enlar ge per object
4 bytes for a reference to Rectangle_shrin k per object

Is this correct so far? If so, then each object would take up at least
36 bytes (conservative estimate). These numbers are probably wrong, but
they should useful to give an approximate understanding of the
situation. The functions take up 320 bytes, so a structure with at
least 9 objects would grow bigger than the total size of the functions.

If we used a prototype, then we would have:

64 bytes for Rectangle_area
64 bytes for Rectangle_perim eter
64 bytes for Rectangle_set_s ize
64 bytes for Rectangle_enlar ge
64 bytes for Rectangle_shrin k

4 bytes for a reference to Rectangle_area in the prototype
4 bytes for a reference to Rectangle_perim eter in the prototype
4 bytes for a reference to Rectangle_set_s ize in the prototype
4 bytes for a reference to Rectangle_enlar ge in the prototype
4 bytes for a reference to Rectangle_shrin k in the prototype

8 bytes for a number type per obejct
8 bytes for a number type per obejct
4 bytes for a reference to the prototype per object

Right? In this case, we have 320 bytes used by the functions, 20 bytes
used by the prototype, and 20 bytes used by each object. Now we nearly
halfed the memory requirements: it takes a structure of 17 objects to
take up more room than the functions.

Thus, it is always good to use a prototype object when you can. Is my
analysis correct?

Sincerely,

Jimmy Cerra

P.S. I called you Lasse, since "L" seemed too short for a greeting. :-)

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #7
James Cerra wrote:
Thus, it is always good to use a prototype object when you can. Is my
analysis correct?


It might be technically correct, however you have just spent a great deal of
time to discuss memory requirements which will most likely never be an
issue.

Take the following code:

<script type="text/javascript">
function MyObject(a, b, c) {
this.a = a;
this.b = b;
this.c = c;

this.d = function() {
alert(a + b + c);
}
this.e = function() {
return (a + b + c);
}
}

var myArray = [];
for (var i = 0; i < 10000; i++) {
myArray.push(
MyObject(
(new Array(1024)).jo in("a"),
(new Array(1024)).jo in("b"),
(new Array(1024)).jo in("c")
)
);
}
</script>

Memory before:
IE6SP1 Memory Usage: 13980KB VM Size: 10428KB
Firefox 0.9.2 Memory Usage: 32840KB VM Size: 27536KB
Memory after:
IE6SP1 Memory Usage: 14784KB VM Size: 11200KB
Firefox 0.9.2 Memory Usage: 33260KB VM Size: 27912KB

I'm sure someone will make an argument about PDAs or embedded devices, but
if you are manipulating > 10,000 client-side Javascript objects on a
low-power computing device, you're probably using the wrong tool for the job
(be it a low-power computing device or client-side Javascript).

Given the highly unscientific figures above, and the fact that the maximum
change when creating 10,000 3KB (at least!) objects was 7% of current memory
usage, it's not something I worry about.

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq

Jul 23 '05 #8
Jimmy Cerra wrote:
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.


There are no classes in JavaScript 1.x, it uses prototype-based
inheritance. Since this is not the only big error in Flanagan's
book (ask Google Groups) I am not sure whether it should be
recommended in the FAQ any further. The most recent edition is
of 2002 and recommends techniques even considered proprietary,
deprecated and/or obsolete at *that* time. Consider what that
would mean for today.
PointedEars
Jul 23 '05 #9
Grant Wagner,
It might be technically correct, however you have just spent a great deal of
time to discuss memory requirements which will most likely never be an
issue.


I understand. However, I happen to be working on a web application in
which performance is a big issue. (See a demo here [1]. It is
similar to IE7 [2]). The script has to transverse and manipulate
large data structures in as short a period of time as possible.
That's why I was curious about the details of JavaScript objects. Of
course, curiosity killed the cat, so... ;-)

--
Jimmy Cerra

[1] http://www.pitt.edu/~jfcst24/2004/05...0.1/index.html

[2] http://dean.edwards.name/ie7/
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3840
by: benevilent | last post by:
Hey, I'm trying to debug the memory allocation in an embedded use of the Python interpreter. The longer I leave my program running the more memory it consumes. The total number of objects in the system is not increasing (many are being allocated and deallocated). Using mtrace I have established that the only memory which is not being
21
3910
by: Rabbit63 | last post by:
Hi: I want to show a set of records in the database table on the clicnt browser. I have two ways to do this (writen in JScript): 1.The first way is: <% var sql = "select firstname from table1"; var obj=new ActiveXObject("ADODB.Recordset");
4
16394
by: Sean | last post by:
I am a little bit confused about memory clean up in VB.NET. (Damn I never thought I'd miss News and Deletes from VC++, but at least I was sure there). If I have some code like: Public Function SomeFunction(ByVal count As Integer) Dim Instance as MyClass For i = 0 to count
6
2878
by: Michael Isaacs | last post by:
Regarding use of enum's, I am wondering what the cost of memory is when creating the enumeration on the calling side, and then using it on the function/method side. See example below. If I understand correctly, what is actually happening on the calling side is an instance of the enum class FavoriteSport is getting created and sent to the PrintFavorite routine with a default value of type int. Is this correct? Say I have a couple hundred uses...
2
1165
by: Peter Hartlén | last post by:
Hi! The basic questions here is how an object is stored in memory. I have an list of a custom object, where the object has a couple of fields, properties and methods. If we pretend that he fields take 24bytes, the properties take 12bytes and the methods take 36bytes of code for this particular object, will the lists memory consumption be (24+12+36)*number of objects in list ?
13
3616
by: Chris Thomasson | last post by:
Here is some info on a C++ allocator prototype I am working on: http://groups.google.com/group/comp.lang.c++/browse_frm/thread/beeee1f61fdbb52c Any tried-and-true techniques for calculating the correct alignment of any C++ type the user can throw at it? For the initial code, I was assuming that the alignment(T) == sizeof(T)... Now that I am so close to being able to release this thing, I wanted to be able to stitch up this loose end. ...
11
2578
by: Alexander Adam | last post by:
Hi! Is there an efficient way to "shorten" an array with C++ Operators without the need to delete it, then reallocate it? I've thought about using reallocate which might do the job but its C and besides that I am using C++ operators new and delete . Besides, would it be faster to use malloc() and free() instead of new and delete ? I can make sure that the types used for those operations will be simple types (most of the time an...
3
1705
by: =?Utf-8?B?VG9tKys7?= | last post by:
When I create an object in VB.NET I define both properties (data) and methods (code). If I have 1,000 instances of this object stored in a Dictionary as Dictionary(of int32, object) then I am obviously repeating the data of the object 1,000 times. If I understand correctly how objects are constructed, the methods (code) is only stored once in memory and referenced by each instance of the object. Thus it does not matter how many methods I...
50
3480
by: arunajob | last post by:
Hi all, If I have a piece of code something like this void main(void) { char * p1="abcdefghijklmn"; ............................................. }
0
8407
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8319
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8837
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8612
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7347
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6175
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2739
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1732
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.