in reply to foreach (each character in string..)?
I would not usually favour it for style and readability that are much better in the split version, but I posted it for completeness.my $c; for ( my $i = 0; $i < length($string); $i++ ) { $c = substr( $string, $i, 1); }
By the way, I noticed that the execution speed is more or less the same; I measured this with Benchmark, and noticed that the longer the string in $string, the comparatively fast the for version gets.
See how the bigger the input $string gets, the bigger the difference in favour of the for version is, going from +5% to +16% in the 30k case.
This is my test code:$string is 3000 bytes Benchmark: running for, split, each for at least 10 CPU seconds... for: 10 wallclock secs (10.31 usr + 0.00 sys = 10.31 CPU) @ 12 +3.73/s (n=1275) split: 10 wallclock secs (10.58 usr + 0.00 sys = 10.58 CPU) @ 11 +7.15/s (n=1240) +5% $string is 10000 bytes Benchmark: running for, split, each for at least 10 CPU seconds... for: 11 wallclock secs (10.33 usr + 0.00 sys = 10.33 CPU) @ 36 +.96/s (n=382) split: 11 wallclock secs (10.44 usr + 0.00 sys = 10.44 CPU) @ 34 +.08/s (n=356) +8% $string is 30000 bytes Benchmark: running for, split, each for at least 10 CPU seconds... for: 10 wallclock secs (10.19 usr + 0.00 sys = 10.19 CPU) @ 12 +.36/s (n=126) split: 10 wallclock secs (10.60 usr + 0.00 sys = 10.60 CPU) @ 10 +.57/s (n=112) +16%
use Benchmark; my $string = "1234567890" x 5000 ; print "\$string is " . length( $string ) . " bytes \n"; timethese(-10,{split=>sub{ for my $c (split //, $string) { } }, for=>sub{ my $c; for ( my $i = 0; $i < length($string); $i++ ) { $c = substr( $string, $i, 1); } }});
|
|---|