Am 01.04.2017 05:59 schrieb "Ryan Joseph" <r...@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;
> begin
>   result.x := _x;
>   result.y := _y;
> end;
>
> procedure TPoint.SetPoint (_x, _y: integer);
> begin
>   x := _x;
>   y := _y;
> end;
>
> 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.

Regards,
Sven
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to