用substr前缀到字符串会更快吗? [英] Is it faster to prepend to a string with substr?

查看:254
本文介绍了用substr前缀到字符串会更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚找到了以substr( $str, 0, 0, $prepend )

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

这比...快吗

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

推荐答案

Optrees

如果我们比较顶部的两个optree

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

底部有

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

我得到的结果是

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

因此,我们可以看到multiconcat节省了一些操作,并且速度更快.看起来还不错,

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";

这篇关于用substr前缀到字符串会更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆