使用 substr 附加到字符串是否更快?

Eva*_*oll 6 perl benchmarking substr micro-optimization

我刚刚找到了前面的代码 substr( $str, 0, 0, $prepend )

my $foo = " world!"
substr( $foo, 0, 0, "Hello " );
Run Code Online (Sandbox Code Playgroud)

这比

my $foo = " world!"
$foo = "Hello $foo";
Run Code Online (Sandbox Code Playgroud)

Eva*_*oll 5

光树

如果我们比较两个 opttrees 顶部有

b     <@> substr[t2] vK/4 ->c
-        <0> ex-pushmark s ->7
7        <0> padsv[$foo:2,3] sM ->8
8        <$> const[IV 0] s ->9
9        <$> const[IV 0] s ->a
a        <$> const[PV "Hello "] s ->b
Run Code Online (Sandbox Code Playgroud)

虽然底部有

8     <+> multiconcat(" world!",-1,7)[$foo:2,3] sK/TARGMY,STRINGIFY ->9
-        <0> ex-pushmark s ->7
7        <0> padsv[$foo:2,3] s ->8
Run Code Online (Sandbox Code Playgroud)

基准测试

我为此创建了一个快速基准,

use Benchmark;
use strict;
use warnings;

sub b_multiconcat {
    my $foo = "world!";
    $foo = "Hello $foo";
    return $foo;
}

sub b_substr {
    my $foo = "world!";
    substr( $foo, 0, 0, "Hello " );
    return $foo;
}

sub b_substr_lvalue {
    my $foo = "world!";
    substr( $foo, 0, 0 ) = "Hello ";
    return $foo;
}

unless ( b_multiconcat() eq b_substr() && b_substr() eq b_substr_lvalue() ) {
    die "they're not all the same";
}

Benchmark::cmpthese( -3, {
    multiconcat   => \&b_multiconcat,
    substr        => \&b_substr,
    substr_lvalue => \&b_substr_lvalue
} );
Run Code Online (Sandbox Code Playgroud)

我得到的结果是,

               Rate              substr    substr_valute   multiconcat
substr         7830854/s            --          -18%          -24%
substr_lvalue  9606148/s           23%            --           -7%
multiconcat   10288066/s           31%            7%            --
Run Code Online (Sandbox Code Playgroud)

所以我们可以看到 multiconcat 节省了一些操作并且速度更快。看起来也好很多,

$foo = "Hello $foo";
Run Code Online (Sandbox Code Playgroud)

  • @Polar Bear,同样,它们都生成完全相同的代码(新版本中的“multiconcat”,旧版本中的“concat”),因此两者都不可能比另一个更快。3%完全在误差范围内。 (6认同)
  • @Polar Bear,它生成与 `$foo = "Hello $foo";` 相同的代码,所以没有必要对其进行基准测试 (4认同)