Hi Guys

Hi Guys, 
I have a small question about Delphi and Memory Use. Maybe someone can explain to me.
For the example class:
TPerson = class
  name: string;
  Phone: string
end;
I will have about 4000 instances of this class;
I need a method called GetNamePhone to return name+phone.
My question is: If I include this method in the class, how much memory will be necessary to store these 4000 instances ? 1pointer for each instance or only one pointer to all instances ?

Comments

  1. I'm not sure I understand your question since the 4000 instances would exist in memory regardless of whether you have that extra method or not, wouldn't they?

    But perhaps this will help: The amount of memory of each instance of a class (an object) is not affected by extra methods in the class. An instance requires enough memory for its own fields, plus those of its ancestors (ie the whole type.) For each method in the class, regardless of how many instances of the class there are, you will get one single copy of a few bytes of the compiled method body somewhere (how big it is depends on what the code is compiled to) and if it is a virtual method, an entry in the virtual method table, which is probably one pointer in size. A VMT is shared between all instances of that class.

    So, roughly speaking, fields add memory for each instance; methods add memory once per class.  In general this is trivial, for both cases, unless you have many many many thousands of objects.

    4000 instances of a class as small as your example is unlikely to use nearly enough memory to worry about the effect, even if it turned out to be per-instance, which it isn't. Maybe if you're compiling for mobile it could be important, but I still doubt it. Which leads me to ask, why are you asking? Are your optimizing something, and if so what? Maybe we can help...

    ReplyDelete
  2. What may be helpful is to know that when you write myPerson.GetNamePhone() the compiler effectively translates that to TPersonGetNamePhone(myPerson), ie a regular function call where the first parameter is the object instance, the first method parameter, if any, becomes the second parameter etc.

    Virtual methods are similar but with a twist as David hinted at above.

    ReplyDelete
  3. My goal was to use the least amount of memory to store all these instances. My real class, of course, has has several methods and properties. Thanks guys: David, Asbjorn and Lars.

    ReplyDelete
  4. Cleidson Barbosa Glad to help.

    I personally tend not to worry too much about instance size (although if you're getting into thousands of objects, I can see why you'd start thinking about it.) Even 4000 objects at, say, 32 bytes each (32 bit; 8 bytes for TObject, 24 bytes for, say, three extra int-sized fields) is only 128KB.

    ReplyDelete

Post a Comment