in reply to tr/abc// won't use string
Here's a short compare in benchmark terms of the two solutions. I added a third alternative using index - which can only be used for fixed strings whereas the other solutions can also use regexes. The following code was used:
The results vary with the length of the pattern searched for. The longer the pattern, the slower the substitution solution (as it has to substitute a longer string). The index version is always slowest. For the case where there are zero occurences of the pattern, all three alternatives take approx. the same time.use strict; use warnings; use Benchmark; our $cnt = 0; our $foo = q/abcdef/ x 10_000; Benchmark::cmpthese( 1000, { 'while' => sub {$cnt++ while $foo =~ /abc/g;}, 'subst' => sub {$cnt = $foo =~ s/abc/abc/g;}, 'index' => sub {my $POS = -1; $cnt++ while (($POS = index($foo,'abc',$POS+1)) > -1);}, }); # prints Benchmark: timing 1000 iterations of index, subst, while... index: 27 wallclock secs (25.09 usr + 0.02 sys = 25.11 CPU) @ 39 +.83/s (n=1000) subst: 15 wallclock secs (14.93 usr + 0.02 sys = 14.95 CPU) @ 66 +.89/s (n=1000) while: 18 wallclock secs (17.08 usr + 0.01 sys = 17.09 CPU) @ 58 +.53/s (n=1000) Rate index while subst index 39.8/s -- -32% -40% while 58.5/s 47% -- -12% subst 66.9/s 68% 14% --
-- Hofmator
|
|---|