in reply to Efficient walk/iterate along a string
The fastest way I've found of accessing the characters of a string is to use chop.
Even if you need to copy the string to avoid its destruction; and reverse it to get the characters in the right order, it still comes out substantially quicker than any other method I've tried.
If you can avoid both the copy and the reverse it gets much faster still, but that's not easy to benchmark due to the destructive process. But if you are reading the records one at a time from a file, you're probably going to overwrite the record at each iteration, so that often doesn't matter in a real application.
#! perl -slw use strict; use Benchmark qw[ cmpthese ]; our $string = 'x'x5000; cmpthese -1, { substr => q[ for ( 0..length( $string)-1 ) { my $c = substr $string, $_, 1; } ], splitArray => q[ my @c=split'',$string; for( 0 .. $#c ){ my $c = $c[$_]; } ], splitFor => q[ for( split'', $string ){ my $c = $_; } ], unpack => q[ for( unpack 'C*', $string ) { my $c = chr; } ], reverseChop => q[ my $s = reverse $string; my $c; $c = $_ while chop $s; ], chop => q[ my $s = $string; my $c; $c = $_ while chop $s; ], ramfile => q[ open my $ram, '<', \$string; my $c; $c = $_ while $_ = getc( $ram ); ], }; __END__ C:\test>873068 Rate splitArray splitFor ramfile substr unpack reverseCh +op chop splitArray 169/s -- -48% -74% -81% -83% -8 +9% -89% splitFor 323/s 91% -- -51% -64% -67% -7 +9% -79% ramfile 654/s 288% 103% -- -27% -34% -5 +7% -58% substr 891/s 428% 176% 36% -- -9% -4 +2% -43% unpack 984/s 484% 205% 51% 10% -- -3 +6% -37% reverseChop 1534/s 809% 376% 135% 72% 56% +-- -1% chop 1555/s 822% 382% 138% 74% 58% +1% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Efficient walk/iterate along a string
by moritz (Cardinal) on Nov 23, 2010 at 12:54 UTC | |
by BrowserUk (Patriarch) on Nov 23, 2010 at 13:29 UTC |