Which is the best implementation(in terms of speed and memory usage) for iterating through a Perl array? Is there any better way? (@Array
need not be retained).
Implementation 1
foreach (@Array)
{
SubRoutine($_);
}
Implementation 2
while($Element=shift(@Array))
{
SubRoutine($Element);
}
Implementation 3
while(scalar(@Array) !=0)
{
$Element=shift(@Array);
SubRoutine($Element);
}
Implementation 4
for my $i (0 .. $#Array)
{
SubRoutine($Array[$i]);
}
Implementation 5
map { SubRoutine($_) } @Array ;
IMO, implementation #1 is typical and being short and idiomatic for Perl trumps the others for that alone. A benchmark of the three choices might offer you insight into speed, at least.
1 is substantially different from 2 and 3, since it leaves the array in tact, whereas the other two leave it empty.
I'd say #3 is pretty wacky and probably less efficient, so forget that.
Which leaves you with #1 and #2, and they do not do the same thing, so one cannot be "better" than the other. If the array is large and you don't need to keep it, generally scope will deal with it (but see NOTE), so generally, #1 is still the clearest and simplest method. Shifting each element off will not speed anything up. Even if there is a need to free the array from the reference, I'd just go:
when done.
In single line to print the element or array.
print $_ for (@array);
NOTE: remember that $_ is internally referring to the element of @array in loop. Any changes made in $_ will reflect in @array; ex.
output: 2 4 6
In terms of speed: #1 and #4, but not by much in most instances.
You could write a benchmark to confirm, but I suspect you'll find #1 and #4 to be slightly faster because the iteration work is done in C instead of Perl, and no needless copying of the array elements occurs. (
$_
is aliased to the element in #1, but #2 and #3 actually copy the scalars from the array.)#5 might be similar.
In terms memory usage: They're all the same except for #5.
for (@a)
is special-cased to avoid flattening the array. The loop iterates over the indexes of the array.In terms of readability: #1.
In terms of flexibility: #1/#4 and #5.
#2 does not support elements that are false. #2 and #3 are destructive.
If you only care about the elements of
@Array
, use:or
If the indices matter, use:
Or, as of
perl
5.12.1, you can use:If you need both the element and its index in the body of the loop,
I would expectusingeach
to be the fastest, but thenyou'll be giving up compatibility with pre-5.12.1perl
s.Some other pattern than these might be appropriate under certain circumstances.
The best way to decide questions like this to benchmark them:
And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi
I get:
So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.
@ikegami also points out that there are quite a few differences in these implimentations other than speed.