Why doesn't the Delphi record size increase when the procedure is turned on?

I have two records with the same fields, and one of them has a set of procedures. Why are both records the same size?

{$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils; type TData = record Age : Byte; Id : Integer; end; TData2 = record Age : Byte; Id : Integer; procedure foo1; procedure foo2; procedure foo3; end; procedure TData2.foo1; begin end; procedure TData2.foo2; begin end; procedure TData2.foo3; begin end; begin try Writeln('SizeOf(TData) = '+ IntToStr(SizeOf(TData))); Writeln('SizeOf(TData2) = '+ IntToStr(SizeOf(TData2))); Readln; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. 
+8
delphi delphi-xe2
source share
2 answers

This is because the record itself refers only to the data that makes up the record, and not to procedures or functions. Procedures and functions are a kind of syntactic sugar to avoid passing the record itself as a parameter: the self variable, which is automatically added by the compiler for you.

Each method that you declare in a record has a different parameter for the record itself, for example:

  TData2 = record Age : Byte; Id : Integer; procedure Foo1; procedure Foo2(SomeParam: Integer); end; 

changes to something equivalent to:

  PData2 = ^TData2; TData2 = record Age : Byte; Id : Integer; end; procedure TData2_Foo1(Self: PData2); procedure TData2_Foo2(Self: PData2; SomeParam: Integer); 

the end of each call you make also changes, for example:

 var Data: TData2; begin Data.Foo1; Data.Foo2(1); end; 

changes for something equivalent:

 var Data: TData2; begin TData2_Foo1(@Data); TData2_Foo1(@Data, 1); end; 

I don't have Delphi on hand to check if a parameter is added at the beginning or at the end of the parameter list, but I hope you get this idea.

Of course, there is no real syntax for this, since it is executed on the fly by the compiler, and thus, for example, the names of the procedures are not changed. I did this in an attempt to understand my answer.

+10
source share

Procedures do not take up space. The compiler will connect them correctly. Their addresses do not have to be in memory at run time for each entry. If you look at the TData2 representation in memory, you will not find the procedure.

0
source share

All Articles