Is it faster to prepend to a string with substr?

浪子不回头ぞ 提交于 2020-05-14 18:42:28

问题


I just found code that prepends with substr( $str, 0, 0, $prepend )

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

Is this any faster than

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

回答1:


Optrees

If we compare the two optrees the top has

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

While the bottom has

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

Benchmarking

I've created a quick benchmark for this,

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

And the results that I got are,

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

So we can see the multiconcat saves a few ops and is somewhat faster. It also looks a lot nicer to say,

$foo = "Hello $foo";


来源:https://stackoverflow.com/questions/61668990/is-it-faster-to-prepend-to-a-string-with-substr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!