Archive

Posts Tagged ‘Perl’

3 Substring methods benchmark

June 23, 2011 Leave a comment
#!/usr/bin/perl
use strict;
use warnings;

my $number='12345678';
my ($first,$second);
for my $i (1..10_000_000) {
    if( $number =~ /^(\d{3}(\d{5}))$/ ) {
        $first=$1;
        $second=$2;
    }
}
time perl reg.pl

real	0m14.066s
user	0m13.974s
sys	0m0.012s
============================================================
#!/usr/bin/perl
use strict;
use warnings;

my $number='12345678';
my ($first,$second);
for my $i (1..10_000_000) {
    ($first, $second)=unpack('a3a5', $number);
}

time perl unpack.pl

real	0m9.427s
user	0m9.321s
sys	0m0.016s
============================================================
#!/usr/bin/perl
use strict;
use warnings;

my $number='12345678';
my ($first,$second);
for my $i (1..10_000_000) {
    $first=substr($number, 0, 3);
    $second=substr($number, 3, 5);
}

time perl substr.pl

real	0m5.945s
user	0m5.846s
sys	0m0.017s

Seems the winner is the good old substr routine.