perl - 使用 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";
推荐阅读
- php - node-server-screenshot 无法在实时 ubundu 服务器上运行
- mongodb - mongodb中的父子查询
- c++ - 为什么这个经过时间(帧时间)计算会锁定我的游戏
- java - 为什么 pageContext.request.contextPath 被解释为 $%7BpageContext.request.contextPath%7D?
- c# - 当我使用来自 UWP 的 Launcher.LaunchUriAsync 转到 MS Edge 时,我可以删除搜索引擎请求吗?
- scrapy - 限制scrapy请求和项目
- regex - 正则表达式可选括号分成强制三组
- java - 使用geotools开发wms服务时如何将地图图像输出到浏览器?
- scala - 如何将 XML 文件中的多列转换规则传递到 Spark 中的 Dataframe?
- c - 如何在给定的数字集合中找到第二大元素?