Write it correctly the first time
Yes, exactly. Then dirty it up to make it go faster if you must. Your sample code is an excellent case in point. If you were processing vast numbers of strings in a highly time critical application and were doing no other processing at all then there may be some justification for using index instead of a regex match and performing the extra checking required to detect a failed match. Otherwise it's a lot clearer to go with the simple regex.
It doesn't help your argument that your unchecked substr sample code gives what would probably be considered the wrong answer when there is no match: the last character of the string. Correct handling of the no match case dirties up the index code and doubles its execution time, but the humble regex is essentially unaffected. Consider:
use strict;
use warnings;
use Benchmark 'cmpthese';
my $str = 'FOO' x 14 . 'ZOOCOO' . ('FOO' x 7);
for my $subName (qw(doSubZ doSubB doSubX doRegZ doRegB)) {
my $result = main->can($subName)->();
$result //= '--undef--';
print "$subName: $result\n";
}
cmpthese(
-1,
{
'substrindexZ' => \&doSubZ,
'substrindexB' => \&doSubB,
'regexpZ' => \&doRegZ,
'regexpB' => \&doRegB,
}
);
sub doSubZ {
return undef if -1 == (my $idx = index ($str, 'ZOO'));
return substr ($str, $idx, 6);
}
sub doSubX {
return substr ($str, index ($str, 'BOO'), 6);
}
sub doSubB {
return undef if -1 == (my $idx = index ($str, 'BOO'));
return substr ($str, $idx, 6);
}
sub doRegZ {
$str =~ /(ZOO.{3})/;
return $1;
}
sub doRegB {
$str =~ /(BOO.{3})/;
return $1;
}
Prints:
doSubZ: ZOOCOO
doSubB: --undef--
doSubX: O
doRegZ: ZOOCOO
doRegB: --undef--
Rate regexpZ substrindexZ substrindexB reg
+expB
regexpZ 1215237/s -- -45% -70%
+-79%
substrindexZ 2198729/s 81% -- -45%
+-62%
substrindexB 4003188/s 229% 82% --
+-30%
regexpB 5733702/s 372% 161% 43%
+ --
True laziness is hard work
|