On Friday, August 10, 2001, at 07:54 , Craig S. Cottingham wrote:

> What about
>
>       $string = reverse $string;
>       $string =~ s/^\s+//;
>       $string = reverse $string;
>
> I haven't had any coffee yet this morning, so I'm probably 
> missing a way to condense that. Time to break out 
> Benchmark.pm....

Wow. The snippet above is roughly twice as fast as a simple 
"$string =~ s/\s+$//;":

        Benchmark: running t01_simple, t02_reverse, each for at 
least 3 CPU seconds...
        t01_simple:  4 wallclock secs ( 3.40 usr +  0.00 sys =  3.40 
CPU) @ 3112.94/s (n=10584)
        t02_reverse:  3 wallclock secs ( 3.14 usr +  0.00 sys =  
3.14 CPU) @ 6520.70/s (n=20475)

I'm using a test string with whitespace at both ends and 
embedded in the middle. I assume (being oblivious to the 
internals of regexes) that the regex engine is being slowed down 
by all the embedded whitespace, having to check each instance 
for end-of-string.

As a quick test, I changed my test string to have whitespace 
only at the end:

        Benchmark: running t01_simple, t02_reverse, each for at 
least 3 CPU seconds...
        t01_simple:  4 wallclock secs ( 3.15 usr +  0.00 sys =  3.15 
CPU) @ 5913.97/s (n=18629)
        t02_reverse:  3 wallclock secs ( 3.27 usr +  0.00 sys =  
3.27 CPU) @ 6903.36/s (n=22574)

My original test script:

        #!/usr/bin/perl -w

        use strict;

        use Benchmark;

        my $alphabet = join '', ' ', ('A'..'Z'), ' ';

        my $full;
        $full .= $alphabet for (1..135);
        $full .= ' ' x 20;

        sub t01_simple
        {
                my $string = $full;

                $string =~ s/\s+$//;

                $string;
        }

        sub t02_reverse
        {
                my $string = $full;

                $string = reverse $string;
                $string =~ s/^\s+//;
                $string = reverse $string;

                $string;
        }

        timethese(0, {
                t01_simple      =>  \&t01_simple,
                t02_reverse     =>  \&t02_reverse,
        });

--
Craig S. Cottingham
[EMAIL PROTECTED]
PGP key available from: 
<http://pgp.ai.mit.edu:11371/pks/lookup?op=get&search=0xA2FFBE41>
ID=0xA2FFBE41, fingerprint=6AA8 2E28 2404 8A95 B8FC 7EFC 136F 
0CEF A2FF BE41

Reply via email to