Inspired by the discussion on @eugene's answer, here are some micro-benchmarks using ActiveState perl 5.10.1 on Windows XP. Of course, my benchmarks suck, so take it with a spoonful of salt.
#!/usr/bin/perl
use strict; use warnings;
use Benchmark qw( cmpthese );
my $x = 'x' x 100;
my $y = '.' . $x;
for my $s ($x, $y) {
printf "%33.33s ...\n\n", $s;
cmpthese -5, {
's///' => sub {
my $z = $s;
$z =~ s{^\.}{foo/bar};
},
'index/substr' => sub {
my $z = $s;
if (0 == index $z, '.') {
substr($z, 0, 1, 'foo/bar');
}
},
'substr/substr' => sub {
my $z = $s;
if ('.' eq substr $z, 0, 1) {
substr($z, 0, 1, 'foo/bar');
}
},
};
print '=' x 40, "\n";
}
Output:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...
Rate index/substr substr/substr s///
index/substr 1622404/s -- -14% -42%
substr/substr 1890621/s 17% -- -32%
s/// 2798715/s 73% 48% --
========================================
.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...
Rate s/// substr/substr index/substr
s/// 367767/s -- -57% -62%
substr/substr 857083/s 133% -- -10%
index/substr 956428/s 160% 12% --
========================================