我想转换ABCDEF
为A,B,C,D,E,F
使用Perl最快的方法是什么?
我有很多字符串要转换,字符串最长可达 32768 字节。所以,我想降低字符串转换的开销。
怎么样
$string =~ s/.\K(?=.)/,/g; # using \K keep escape
$string =~ s/(?<=.)(?=.)/,/g; # pure lookaround assertion
或者
$string = join ",", split(//, $string);
要找到最快的解决方案,请使用Benchmark
.
额外学分:
这是我尝试过的基准测试的结果。令人惊讶的是,\K
逃逸比纯环顾快得多,后者与拆分/连接差不多快。
use strict;
use warnings;
use Benchmark qw(cmpthese);
my $string = "ABCDEF" x 1000;
cmpthese(-1, {
keep => 'my $s = $string; $s =~ s/.\K(?=.)/,/g',
lookaround => 'my $s = $string; $s =~ s/(?<=.)(?=.)/,/g',
splitjoin => 'my $s = $string; $s = join ",", split(//, $string)'
});
输出:
Rate splitjoin lookaround keep
splitjoin 6546367/s -- -6% -47%
lookaround 6985568/s 7% -- -44%
keep 12392841/s 89% 77% --
$ perl -le 'print join(",", unpack("(A)*", "hello"))'
h,e,l,l,o
$ perl -le 'print join(",", unpack("C*", "hello"))'
104,101,108,108,111
$ perl -le 'print join(",", unpack("(H2)*", "hello"))'
68,65,6c,6c,6f
my $str = "ABCDEFGHIJKL";
my @chars = $str =~ /./sg;
print join ",", @chars;
如果您尝试以较低的开销打印字符串,您可能只想在解析字符串时打印字符串,而不是在内存中进行整个转换,即
while (m/(.)\B/gc){
print "$1,";
};
if (m/\G(.)/) {
print "$1\n";
}