Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi object memory allocation

Tags:

delphi

In Delphi, if I have a variable myObject : MyClass, and MyClass has a property that is a fixed-length array with 300 integers in it, when will the memory for it be allocated?

  • When the scope of myObject is entered?
  • When I call myObject := MyClass.Create; (constructor)?
like image 663
Nostrovje Avatar asked Oct 21 '10 15:10

Nostrovje


2 Answers

Fixed-length arrays are allocated inline, so it exists as part of the instance size of MyClass and it gets allocated when you call the constructor.

like image 139
Mason Wheeler Avatar answered Oct 23 '22 10:10

Mason Wheeler


If you really mean the object has a property, then no space at all is allocated for it. Properties are generalized interfaces to some other mode of access, either a field or a function.

If the property is backed by a field of the object, then, as Mason explained, the field exists as part of the object itself; the array's length directly affects the total size of the object (as given by the TObject.InstanceSize method). The field has memory; the property doesn't.

If the property is backed by a function, then the function's return value generally gets allocated on the caller's stack and passed in as a "var" parameter. The function fills it and returns to the caller. Again, the property itself has no memory allocated for it.

You could have a hundred properties on an object that's only four bytes long (which is the minimum size for objects).

If, however, you actually meant a field, then it is allocated as part of the object during the call to TObject.NewInstance. That method is called as part of the outer constructor's prologue ( as opposed to any calls to inherited constructors).

like image 5
Rob Kennedy Avatar answered Oct 23 '22 12:10

Rob Kennedy