in reply to More Help with Regex

Update: i added petral's and impossiblerobot's routines to the comparison...

although my solution was complex and used regex mojo, chipmunk's is by far the faster of the two. impossiblerobot's first is fastest of all, becase there's no real thinking involved. consider

#!/usr/local/bin/perl -w use strict; use Benchmark; my $s = '00a0c801adc6'; timethese(100000,{ particle => sub { my $str = $s; $str =~ s/([\w]{2})(?!$)/$1:/gio; }, chipmunk => sub { my $str = $s; $str = join(':', $str =~ /../g); }, petral => sub { my $str = $s; $str = join(':', split /(?=(?:..)+$)/,$str); }, robot1 => sub { my $str = $s; $str = join(':', unpack 'a2a2a2a2a2a2', $str); }, robot2 => sub { my $str = $s; $str = join(':', unpack('a2' x (length($str)/2), $str)); }, });
which results, on my 450MHz, 768MB ram, win98 box, in:
C:\WINDOWS\Desktop>perl test_mac.pl Benchmark: timing 100000 iterations of chipmunk, particle, petral, rob +ot1, robot2... chipmunk: 3 wallclock secs ( 2.52 usr + 0.00 sys = 2.52 CPU) @ 396 +82.54/s (n=100000) particle: 6 wallclock secs ( 6.48 usr + 0.00 sys = 6.48 CPU) @ 154 +32.10/s (n=100000) petral: 5 wallclock secs ( 6.05 usr + 0.00 sys = 6.05 CPU) @ 165 +28.93/s (n=100000) robot1: 2 wallclock secs ( 1.27 usr + 0.00 sys = 1.27 CPU) @ 787 +40.16/s (n=100000) robot2: 3 wallclock secs ( 3.02 usr + 0.00 sys = 3.02 CPU) @ 331 +12.58/s (n=100000)
this goes to show you just how much more time regexes can add to your algorithm.

~Particle

Replies are listed 'Best First'.
Re: Re: More Help with Regex
by petral (Curate) on Jan 31, 2002 at 21:28 UTC
    Thanks for the times. But just to balance it out, yours could easily be considered the most straightforward:

    (cleaned up a little):     $str =~ s/..(?!$)/$&:/g;

    says "insert a colon between each pair of characters" at least as clearly as any of the others. Slight update: That should be s/..(?=..)/$&:/g, to make the point about readability.

      p