2

I am doing a program that solves a system of Congruences (Algebra) and I have created a class called TCongruence with constructor, functions, class functions and so on. I have declared a private variable:

private
 x: array of TCongruence;

When I try to fill this array I am writing this code:

counter := counter + 1;
SetLength(x, counter);
x[counter-1] := TCongruence.Create(...);

I have understood that this code works after some time I have spent on these 3 lines because my original code was something like this:

counter := counter + 1;
SetLength(x, counter);
tmp := TCongruence.Create(...);
x[counter-1] := tmp;

Of course I have tmp: TCongruence. Why is the second block of code wrong? Class are references so I thought that I could do something like that given the fact that I am not calling Free on tmp.


Wrong = at compile time it's good but at runtime when I access the array I have weird values.

Raffaele Rossi
  • 2,997
  • 4
  • 31
  • 62

2 Answers2

3

There is no practical difference between the two variants. It seems a little wasteful to assign to a intermediate local variable, but it won't change the behaviour of your program.

If there is a difference in behaviour, then that will be due to other factors, in the rest of your program that we cannot see.

Finally, growing arrays one element at a time is a little clunky, potentially slow, and can result in fragmented memory. It would make more sense, typically, to use a class like TList<TCongruence> or TObjectList<TCongruence>. Then you could write:

List.Add(TCongruence.Create(...))
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Ok thank you. Counter cannot be bigger than 20 so I wanted to use the dynamic array approach. I didn't use the Generic approach beucase I have read that they increase the final exe/apk dimension. If they really do, is that by a lot? – Raffaele Rossi May 07 '17 at 15:56
  • Why do you care about the exe size? If that was important to you you wouldn't choose Delphi which really is the worst tool available in terms of exe size. If counter can't be bigger than 20 use a static array with fixed size. – David Heffernan May 07 '17 at 15:57
  • Might as well as include the unit which is required to get the List object from. – IOviSpot Feb 27 '22 at 13:29
2

You can just write x := x + [TCongruence.Create(..)], it is more readable.

EugeneK
  • 2,164
  • 1
  • 16
  • 21