http://qs321.pair.com?node_id=743725

lefthanded has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I'm fairly new to Perl, and I have a basic question about how foreach loops work. Say you want to iterate through an array, @a, in some particular order, but @a is not yet sorted in that order. Would it be better (i.e., faster) to sort @a beforehand, and then use it in the loop, or is it fine to sort in-line with the loop? Basically, if I don't care about preserving the current order of @a, which of these two methods is preferred:

Method 1:
@a = sort @a; foreach (@a) { ... }
Method 2:
foreach (sort @a) { ... }
I prefer Method 2 simply because it's slightly less code, but I'm concerned that maybe it's re-sorting @a on each iteration, which would be bad. I notice that the following code runs forever:
my @a = (1); foreach (@a) { push @a, 1; }
So the loop doesn't fix at its start what it's going to iterate through, which is what makes me think Method 2 might be inefficient. Although maybe the loop decides that it's going to iterate through @a, whatever that may be, whether it changes or not within. So it is fixed in a sense, in which case Method 2 is fine I think, although really now I'm just more confused.

Thanks for any insight into how this actually works.