in reply to Re: Replacing whitespace with null
in thread Replacing whitespace with null

I cobbled this together based on a post on clpm from several years ago.

tr beats out s by between 4 and over 10 to 1 if I have interpreted this correctly.

use strict; use Benchmark; my $string1 = join '', map rand() < 0.4 ? 'x' : ' ', 1 .. 100; my $string2 = join '', map rand() < 0.4 ? 'x' : ' ', 1 .. 10000; printf "Case 1 deletes %3d of %4d characters\n", $string1 =~ tr/ / /, length $string1; printf "Case 2 deletes %3d of %4d characters\n", $string2 =~ tr/ / /, length $string2; timethese( 10000, { tr1 => sub { my $a = $string1; $a =~ tr/\n\t //d}, s1 => sub { my $a = $string1; $a =~ s/\s//g}, tr2 => sub { my $a = $string2; $a =~ tr/\n\t //d}, s2 => sub { my $a = $string2; $a =~ s/\s//g}, }); __END__ Case 1 deletes 7 of 10 characters Case 2 deletes 592 of 1000 characters Benchmark: timing 100000 iterations of s1, s2, tr1, tr2... s1: 2 wallclock secs ( 1.13 usr + 0.00 sys = 1.13 CPU) @ 88 +339.22/s (n=100000) s2: 54 wallclock secs (52.58 usr + 0.00 sys = 52.58 CPU) @ 19 +01.68/s (n=100000) tr1: 0 wallclock secs ( 0.30 usr + 0.00 sys = 0.30 CPU) @ 33 +2225.91/s (n=100000) (warning: too few iterations for a reliable count) tr2: 3 wallclock secs ( 4.34 usr + 0.00 sys = 4.34 CPU) @ 23 +062.73/s (n=100000) Case 1 deletes 5 of 10 characters Case 2 deletes 615 of 1000 characters Benchmark: timing 100000 iterations of s1, s2, tr1, tr2... s1: 1 wallclock secs ( 0.97 usr + 0.00 sys = 0.97 CPU) @ 10 +2880.66/s (n=100000) s2: 54 wallclock secs (54.22 usr + 0.00 sys = 54.22 CPU) @ 18 +44.37/s (n=100000) tr1: 1 wallclock secs ( 0.31 usr + 0.00 sys = 0.31 CPU) @ 32 +1543.41/s (n=100000) (warning: too few iterations for a reliable count) tr2: 5 wallclock secs ( 4.39 usr + 0.00 sys = 4.39 CPU) @ 22 +753.13/s (n=100000) Case 1 deletes 54 of 100 characters Case 2 deletes 5999 of 10000 characters Benchmark: timing 10000 iterations of s1, s2, tr1, tr2... s1: 0 wallclock secs ( 0.54 usr + 0.00 sys = 0.54 CPU) @ 18 +484.29/s (n=10000) s2: 54 wallclock secs (52.71 usr + 0.01 sys = 52.72 CPU) @ 18 +9.66/s (n=10000) tr1: 0 wallclock secs ( 0.06 usr + 0.00 sys = 0.06 CPU) @ 16 +6666.67/s (n=10000) (warning: too few iterations for a reliable count) tr2: 4 wallclock secs ( 4.30 usr + 0.00 sys = 4.30 CPU) @ 23 +27.75/s (n=10000)