yes, tr/// is not a regex, where s/// is. This means that tr/// should move faster. Let's find out! I'm using 3 sets of randomly generated data, and removing any occurence of the letter 'e' in the string. The results? A winner is tr///!
use Benchmark;
$reps=500000;
$x.=("a".."z")[rand 26] for (1..256);
Benchmark::cmpthese($reps, {
'sub256' => '$_=$x;s/e//g;',
'trn256' => '$_=$x;tr/e//d;',
});
print "-"x40,"\n";
$x="";
$x.=("a".."z")[rand 26] for (1..1024);
Benchmark::cmpthese($reps, {
'sub1024' => '$_=$x;s/e//g;',
'trn1024' => '$_=$x;tr/e//d;',
});
print "-"x40,"\n";
$x="";
$x.=("a".."z")[rand 26] for (1..5120);
Benchmark::cmpthese($reps, {
'sub5k' => '$_=$x;s/e//g;',
'trn5k' => '$_=$x;tr/e//d;',
});
print "-"x40,"\n";
Benchmark: timing 500000 iterations of sub256, trn256...
sub256: 3 wallclock secs ( 3.84 usr + 0.00 sys = 3.84 CPU) @ 130208.33/s (n=500000)
trn256: 2 wallclock secs ( 1.81 usr + 0.00 sys = 1.81 CPU) @ 276243.09/s (n=500000)
Rate sub256 trn256
sub256 130208/s -- -53%
trn256 276243/s 112% --
----------------------------------------
Benchmark: timing 500000 iterations of sub1024, trn1024...
sub1024: 15 wallclock secs (14.56 usr + 0.00 sys = 14.56 CPU) @ 34340.66/s (n=500000)
trn1024: 6 wallclock secs ( 6.81 usr + 0.00 sys = 6.81 CPU) @ 73421.44/s (n=500000)
Rate sub1024 trn1024
sub1024 34341/s -- -53%
trn1024 73421/s 114% --
----------------------------------------
Benchmark: timing 500000 iterations of sub5k, trn5k...
sub5k: 66 wallclock secs (65.36 usr + 0.00 sys = 65.36 CPU) @ 7649.94/s (n=500000)
trn5k: 31 wallclock secs (30.64 usr + 0.00 sys = 30.64 CPU) @ 16318.54/s (n=500000)
Rate sub5k trn5k
sub5k 7650/s -- -53%
trn5k 16319/s 113% --
----------------------------------------
|