On Tuesday, June 12, 2001, at 03:20 , David J. Iberri wrote:

> I know there are some cleaner ways to do this, but they slip my 
> mind for the
> moment... :-)

Mind you, I ran these tests in Perl 5.6.1 on debian-powerpc, but 
the results should be representative.

#!/usr/bin/perl -w
# macperltest

#use strict;
use Benchmark;

my $initial_string = "first value: <xml1> sec value: <xml2>";
my %hash = (
        "<xml1>" => 33,
        "<xml2>" => 44,
);
my $re = '(' . join('|', keys %hash) . ')';
my $pre = qr/$re/;

my $code1 = sub
{
        my $string = $initial_string;
};

my $code2 = sub
{
        my $string = $initial_string;

        while (my ($key, $value) = each %hash)
        {
                $string =~ s/$key/$value/i;
        }
};

my $code3 = sub
{
        my $string = $initial_string;
        $string =~ s/$re/$hash{$1}/gi;
};

my $code4 = sub
{
        my $string = $initial_string;
        $string =~ s/$pre/$hash{$1}/gi;
};

timethese($ARGV[0], {
        empty => $code1,
        loop => $code2,
        regexp => $code3,
        precomp => $code4,
});

1;
__END__

craigc@scooter:~$ ./macperltest 100000
Benchmark: timing 100000 iterations of empty, loop, precomp, regexp...
      empty:  2 wallclock secs ( 0.67 usr +  0.00 sys =  0.67 
CPU) @ 149253.73/s (n=100000)
       loop: 104 wallclock secs (52.15 usr +  0.01 sys = 52.16 
CPU) @ 1917.18/s (n=100000)
    precomp: 72 wallclock secs (36.20 usr +  0.00 sys = 36.20 
CPU) @ 2762.43/s (n=100000)
     regexp: 76 wallclock secs (38.08 usr +  0.01 sys = 38.09 
CPU) @ 2625.36/s (n=100000)

Conclusion: Using one big regular expression is much faster than 
an explicit loop. Copying the initial string adds an 
insignificant amount of time to each iteration.

--
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