创建可写匿名 scalar/string 的最有效方法?
Most efficient way to create a writable anonymous scalar/string?
create/allocate 匿名可写 scalar/string 的最佳方法是什么? perlref
文档中有一段:
*foo{THING} returns undef if that particular THING hasn't been used yet,
except in the case of scalars. *foo{SCALAR} returns a reference to an
anonymous scalar if $foo hasn't been used yet. This might change in a
future release.
虽然那是不可靠的。如果包中存在$foo
,则结果不再是匿名引用
我尝试过的替代方法:
my $ref=\""; #Reference to a literal. NOT writable of course
my $ref=\("".""); #Concatenation of two empty strings.
my $ref=\(""x0); #String repeat zero times
my $ref=\join("",("",));
sub newString{
my $string="";
$string;
}
my $ref=newString(); #Ref from lexical in sub
更新基准测试与响应:
我的(过于简单化?)基准:
cmpthese(10000000,
{
concat=>sub { my $ref=\(""."");},
repeat=>sub { my $ref=\(""x0);},
sub=>sub { my $ref=newString},
join=>sub {my $ref=\join("","")},
auto=>sub {my $ref; $$ref="";},
do=>sub {my $ref=do{\ (my $x = "") }}
}
给出:
Rate concat join repeat sub do auto
concat 7633588/s -- -2% -6% -6% -37% -55%
join 7812500/s 2% -- -4% -4% -35% -54%
repeat 8130081/s 7% 4% -- -0% -33% -52%
sub 8130081/s 7% 4% 0% -- -33% -52%
do 12048193/s 58% 54% 48% 48% -- -29%
auto 16949153/s 122% 117% 108% 108% 41% --
do方法(上面的do)相比起来也很快!谢谢乔罗巴。
我假设自动激活(上面的自动)是 zdim 的答案是如何工作的。我什至没有那样考虑!谢谢
一种方法:只需引入符号,并在使用时将其设为所需的类型
my $ref;
...
$$ref = q(word);
create/allocate 匿名可写 scalar/string 的最佳方法是什么? perlref
文档中有一段:
*foo{THING} returns undef if that particular THING hasn't been used yet,
except in the case of scalars. *foo{SCALAR} returns a reference to an
anonymous scalar if $foo hasn't been used yet. This might change in a
future release.
虽然那是不可靠的。如果包中存在$foo
,则结果不再是匿名引用
我尝试过的替代方法:
my $ref=\""; #Reference to a literal. NOT writable of course
my $ref=\("".""); #Concatenation of two empty strings.
my $ref=\(""x0); #String repeat zero times
my $ref=\join("",("",));
sub newString{
my $string="";
$string;
}
my $ref=newString(); #Ref from lexical in sub
更新基准测试与响应:
我的(过于简单化?)基准:
cmpthese(10000000,
{
concat=>sub { my $ref=\(""."");},
repeat=>sub { my $ref=\(""x0);},
sub=>sub { my $ref=newString},
join=>sub {my $ref=\join("","")},
auto=>sub {my $ref; $$ref="";},
do=>sub {my $ref=do{\ (my $x = "") }}
}
给出:
Rate concat join repeat sub do auto
concat 7633588/s -- -2% -6% -6% -37% -55%
join 7812500/s 2% -- -4% -4% -35% -54%
repeat 8130081/s 7% 4% -- -0% -33% -52%
sub 8130081/s 7% 4% 0% -- -33% -52%
do 12048193/s 58% 54% 48% 48% -- -29%
auto 16949153/s 122% 117% 108% 108% 41% --
do方法(上面的do)相比起来也很快!谢谢乔罗巴。 我假设自动激活(上面的自动)是 zdim 的答案是如何工作的。我什至没有那样考虑!谢谢
一种方法:只需引入符号,并在使用时将其设为所需的类型
my $ref;
...
$$ref = q(word);