Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: How to traverse an array as fast as possible?

by ciderpunx (Vicar)
on Jun 17, 2009 at 07:29 UTC ( #772264=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://772264]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2020-10-01 12:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (12 votes). Check out past polls.

    Notices?