Angeregt durch die Diskussion zu @eugenes Antwort, hier einige Micro-Benchmarks mit ActiveState perl 5.10.1 auf Windows XP. Natürlich, meine Benchmarks sind schlecht nehmen Sie es also mit einem Löffel Salz.
#!/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";
}
Ausgabe:
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% --
========================================