perl5 icon indicating copy to clipboard operation
perl5 copied to clipboard

Optimise foreach on builtin::indexed

Open leonerd opened this issue 1 year ago • 1 comments

Rather than generating an entire temporary list that is twice as big as the original array, instead set a flag on the OP_ITER that tells it to set one of the iteration variables to the current array index and use the same CXt_LOOP_ARY optimisastion that regular foreach over an array would use.

Currently this is a work-in-progress:

  • Consider whether builtin::indexed LIST... should do the same optimisation

  • Write perldelta

  • This set of changes requires a perldelta entry, and it is not included but I'll write something before un-drafting

leonerd avatar Oct 02 '24 17:10 leonerd

This change does have the potential impact that, before it, any modifications to the iterated-on array that happen during the body of its own foreach loop would not get seen, whereas now they would. This is the same issue that single-variable foreach on a plain array already had, so it's not new. But it is a change for existing code that already calls this function.

leonerd avatar Oct 02 '24 17:10 leonerd

Deparse needs an update:

$ ./perl -Ilib -MO=Deparse -Mbuiltin=indexed -e 'for my ($i, $v) (indexed @ARGV) { print "$i: $v\n"; }' 1 2 3
use builtin (split(/,/, 'indexed', 0));
foreach my ($i, $v) (@ARGV) {
    print "${i}: $v\n";
}
-e syntax OK

tonycoz avatar Oct 29 '24 03:10 tonycoz

Looks ok otherwise

tonycoz avatar Oct 29 '24 03:10 tonycoz

This change does have the potential impact that, before it, any modifications to the iterated-on array that happen during the body of its own foreach loop would not get seen, whereas now they would. This is the same issue that single-variable foreach on a plain array already had, so it's not new. But it is a change for existing code that already calls this function.

Consistency seems good, and the foreach docs basically say "don't do this" already. But maybe this change should have a brief mention in perldelta, since this feature isnt experimental anymore?

Grinnz avatar Oct 29 '24 04:10 Grinnz

Added some Deparse support and repushed. Should be good now.

leonerd avatar Nov 06 '24 19:11 leonerd