簡體   English   中英

使用 substr 在字符串前面添加更快嗎?

[英]Is it faster to prepend to a string with substr?

我剛剛找到了以substr( $str, 0, 0, $prepend )的代碼

my $foo = " world!"
substr( $foo, 0, 0, "Hello " );

這比

my $foo = " world!"
$foo = "Hello $foo";

歐普樹

如果我們比較兩個 optree,頂部有

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

雖然底部有

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

基准測試

我為此創建了一個快速基准,

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
} );

我得到的結果是,

               Rate              substr    substr_valute   multiconcat
substr         7830854/s            --          -18%          -24%
substr_lvalue  9606148/s           23%            --           -7%
multiconcat   10288066/s           31%            7%            --

所以我們可以看到 multiconcat 節省了一些操作並且速度更快。 說起來也好看多了,

$foo = "Hello $foo";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM