substr vs regex

Matt Lawrence matt.lawrence at virgin.net
Mon Sep 3 12:11:07 BST 2007


Greg McCarroll wrote:
> On Mon, Sep 03, 2007 at 10:26:12AM +0100, alex at owal.co.uk wrote:
>   
>   
>> have recommended substr to because you "dont need to bring out the big
>> guns".
>>     
>
> write the damn benchmark hippy ;-)
>
>   
I wrote up a quick one just for fun. As predicted, regex was slower than
substr and degraded with string length.

Oddly, though, substr seems to clock in slightly faster on a long string
than a shorter one. It's not a big difference, but it's been consistent
over half a dozen runs.


use strict;
use warnings;

use Benchmark qw( cmpthese );

my @strings = (
    'x' x 1_000,
    'x' x 1_000_000,
);

cmpthese(-10, {
    regex_short     => sub { $strings[0] =~ /(.)\z/ },
    regex_long      => sub { $strings[1] =~ /(.)\z/ },
    substr_short    => sub { substr( $strings[0], -1 ) },
    substr_long     => sub { substr( $strings[1], -1 ) },
});

Results:

                  Rate   regex_long  regex_short substr_short  substr_long
regex_long       761/s           --        -100%        -100%        -100%
regex_short   463242/s       60745%           --         -82%         -84%
substr_short 2506613/s      329133%         441%           --         -15%
substr_long  2936844/s      385642%         534%          17%           --


Can anyone enlighten me as to why this might be?

Matt




More information about the london.pm mailing list