[Wellington-pm] Stripping spaces.

michael at diaspora.gen.nz michael at diaspora.gen.nz
Mon Oct 11 06:09:29 CDT 2004


At the meeting tonight, the regexp expression:

    s/^\s+|\s+$//g

was discussed, and whether or not it was more or less efficient than:

    s/^\s+//g; s/\s+$//g;

(ie, if splitting the expression in two led to better performance).
The answer is, for some reason, it does.  This is probably a bug or
something, but I don't care enough to file it as one.

Viz:

pivot$ perl test_re.pl 
Benchmark: timing 10000 iterations of Combined, Combined_m,
Combined_s, Split...
  Combined: 32 wallclock secs (32.78 usr +  0.00 sys = 32.78 CPU) @
305.06/s (n=10000)
Combined_m: 34 wallclock secs (33.44 usr +  0.01 sys = 33.45 CPU) @
298.95/s (n=10000)
Combined_s: 34 wallclock secs (33.27 usr +  0.02 sys = 33.29 CPU) @
300.39/s (n=10000)
     Split:  1 wallclock secs ( 0.94 usr +  0.00 sys =  0.94 CPU) @
10638.30/s (n=10000)
pivot$ perl -v

This is perl, v5.8.4 built for i386-linux-thread-multi

...

pivot$ cat test_re.pl
#!perl
use Benchmark qw!:all!;

my $string_spaces  = ' ' . 'a' x 2000 . ' ';
my $string_nospace = 'a' x 2000;

timethese(10_000, {
    'Combined' => sub {
        my $s = $string_spaces;
        $s =~ s/^\s+|\s+$//g;
        $s = $string_nospace;
        $s =~ s/^\s+|\s+$//g;
    },
    'Split' => sub {
        my $s = $string_spaces;
        $s =~ s/^\s+//g; $s =~ s/\s+$//g;
        $s = $string_nospace;
        $s =~ s/^\s+//g; $s =~ s/\s+$//g;
    },
    'Combined_s' => sub {
        my $s = $string_spaces;
        $s =~ s/^\s+|\s+$//sg;
        $s = $string_nospace;
        $s =~ s/^\s+|\s+$//sg;
    },
    'Combined_m' => sub {
        my $s = $string_spaces;
        $s =~ s/^\s+|\s+$//mg;
        $s = $string_nospace;
        $s =~ s/^\s+|\s+$//mg;
    },
});



More information about the Wellington-pm mailing list