[fpc-pascal] Setting record values
pascaldragon at googlemail.com
Sat Apr 1 09:46:10 CEST 2017
Am 01.04.2017 05:59 schrieb "Ryan Joseph" <ryan at thealchemistguild.com>:
> I’ve been using a design pattern in my code which I think is probably
pretty stupid so I’d like to make sure. Assume I have a type like TPoint
below and I want to set the value I’ll doing something like point :=
PointMake(x, y). How does the compiler handle this? It probably has to
allocate some memory on the heap so shouldn’t I always be setting values
using the alternative TPoint.SetPoint? It’s maybe not a big deal but it’s
something I’d like to clear up if it’s inefficient.
Records are only located on the stack (or in case of global variables the
data sections). If you want them on the heap then you'd need to explicitly
do that using pointers.
> function PointMake (_x, _y: integer): TPoint;
> result.x := _x;
> result.y := _y;
> procedure TPoint.SetPoint (_x, _y: integer);
> x := _x;
> y := _y;
> same outcome but which is more efficient?
I haven't looked at it in detail, but it could be that both have similar
efficiency. You could also add "inline" to the MakePoint function which
should get rid of a potential temporary variable if the compiler doesn't do
that already anyway.
Alternatively you could also declare a constructor "TPoint.Make" or so
(that despite its name doesn't do any dynamic memory allocation either)
which you can declare as inline as well.
In the end you can always check the assembler code.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the fpc-pascal