0

What happens if inline variables are used inside a loop:

for i := 1 to N do
  begin
  for var j := 1 to M do
    begin
      { Do something with i and j }
    end;
  end;

The scope of the variable j is only the inner loop. Does this mean that the memory for j will be allocated and deallocated N times? This may cause quite some performance penalty in tight loops.

Matej
  • 442
  • 3
  • 9
  • I just did a quick test, and it seems like the compiler generates identical code for both variants (old-school local vars and inline for loop vars). – Andreas Rejbrand Dec 20 '20 at 21:18
  • You might also be interested in https://blog.grijjy.com/2018/11/02/inline-variables-can-increase-performance/. – Andreas Rejbrand Dec 20 '20 at 21:21
  • It's a local variable. Allocation of local variables is free. – David Heffernan Dec 20 '20 at 22:14
  • Local variables are allocated from the stack not the heap so are essentially free. – Brian Dec 20 '20 at 23:36
  • The variable is on the stack. It's allocated on the first pass, and then that same storage will be used for subsequent passes through the loop. There's no new allocations. It's no different than any other local variable. It's the same as if you'd allocated both `i` and `j` in the `var` block at the beginning of a procedure as far as memory allocation goes; the only difference is visibility. – Ken White Dec 21 '20 at 03:25

0 Answers0