Am 20.06.2022 um 03:37 schrieb Hairy Pixels:

On Jun 19, 2022, at 10:04 PM, Sven Barth <pascaldra...@googlemail.com> wrote:

As you can see the allocation only happens once and not all the time.
What might be worse however is the optimization behavior as in this example the 
compiler wouldn't optimize the counter variable into a regvar with enabled 
optimizations (however in case of a nested function the compiler wouldn't do 
this either if the function isn't inlined).


I’m saying if the OUTER method is in a tight loop (Foo in this example) you’re 
in trouble because it now contains an allocation which is unexpected.

In that case we're in the same territory as always: ensure that you know what your code does. It's the same reason why adding character by character to a managed String is slower then allocating the string once and then setting the characters. And I think it's very seldom that someone uses a function reference that does not leave the scope of the surrounding function.

  In fact if this happened within a class wouldn’t it capture and initialize 
all the classes fields also or does it know to only use the fields which are 
encountered in the function body?
If you use a function reference inside a method and access one of the class' fields then it's only Self that's captured.
Either way the reference never leaves the calling scope and thus is wasted and 
should be optimized away to something which exists on the stack, like “is 
nested”.
If the compiler can proove that the function reference never leaves the scope (that means no assignment to global variables, out/var parameters, the Result variable, passing on to some other function or conversion to pointer (and I'm sure there are others)) and the function reference isn't used as an interface then and only then the compiler could reduce this to something else. But that's an optimization for another day and in my opinion such a rarlely used usecase that it's simply not worth it.

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

Reply via email to