in reply to Re^2: Faster indexing an array
in thread Faster indexing an array

you didn't tell us that you need only an interval out of the array, the fastest approach with my version of Perl is iterating over an interval or array slice

DB<173> use Time::HiRes qw/time/ DB<174> @x=();$t=time; for (my $i=$start; $i<=$end;$i++) { push @x, +$a[$i]}; print time-$t 0.21531081199646 DB<175> @y=(); $t=time; push @y, $_ for @a[$start..$end]; print time +-$t 0.1353440284729 DB<176> @z=();$t=time; push @z, $a[$_] for $start..$end; print time- +$t 0.142512083053589

(you are welcome to do proper benchmarking =)

but optimizing or inlining &$keyGen( $element, @_ ) should lead to much more efficiency, since 25% of 15% doesn't count much!!!

update

of course you could directly iterate over the values of a hash slice of an array slice... :)

DB<180> %h=(); $i=$start; $t=time; push @$_, $i++ for @h{@a[$start.. +$end]}; print time-$t => 1 0.427901983261108

BTW: @a=0..1e6;$start=1e5;$end=2*$start;

Cheers Rolf

(addicted to the Perl Programming Language and ☆☆☆☆ :)

Replies are listed 'Best First'.
Re^4: Faster indexing an array
by wollmers (Scribe) on Sep 20, 2014 at 06:54 UTC

    It's not my code, it's from Algorithm::Diff. Of course, A::Diff could be faster, maybe I take over the module.