http://www.perlmonks.org?node_id=772264


in reply to How to traverse an array as fast as possible?

foreach on my machine.
#!/usr/bin/perl use warnings; use strict; use Benchmark qw(:all); my @bigarray; for(1..100000) { push @bigarray, "A randomish string for testing arrays with realisti +c data" ; } timethese(100, { while_shift => sub{ my @array = @bigarray; while (my $value=shift @array){} }, while_pop => sub{ my @array = @bigarray; while (my $value=pop @array){} }, for_each => sub{ my @array = @bigarray; foreach my $value (@array){} }, for_loop => sub{ my @array = @bigarray; for (my $i=0;$i<=@array;$i++) { my $value=$array[$i]; }}, });
Gives me:
$ perl a.pl Benchmark: timing 100 iterations of for_each, for_loop, while_pop, whi +le_shift... for_each: 4 wallclock secs ( 3.85 usr + 0.01 sys = 3.86 CPU) @ 25 +.91/s (n=100) for_loop: 7 wallclock secs ( 7.36 usr + 0.01 sys = 7.37 CPU) @ 13 +.57/s (n=100) while_pop: 5 wallclock secs ( 5.35 usr + 0.00 sys = 5.35 CPU) @ 18 +.69/s (n=100) while_shift: 5 wallclock secs ( 5.38 usr + 0.00 sys = 5.38 CPU) @ 1 +8.59/s (n=100)
--
Linux, perl, punk rock, cider: charlieharvey.org.uk.