drclaw
drclaw

Reputation: 2503

Most efficient way to create a writable anonymous scalar/string?

What is the best way to create/allocate an anonymous writable scalar/string? There's a paragraph in the perlref doc:

*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.

That is unreliable though. If there exists $foo in the package, the result is no longer an anonymous reference.

Alternative methods I've tried:

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

Updated benchmarking with responses:

My (over simplistic?) benchmark:

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 = "") }}
}

Gives:

             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%     --

The do method (do above) is also very quick in comparison! Thanks choroba. I'm assuming the autovivication (auto above) is how zdim's answer works. I didn't even consider that way! Thanks

Upvotes: 2

Views: 72

Answers (1)

zdim
zdim

Reputation: 66899

One way: just introduce the symbol, and make it the desired type on use

my $ref;
...
$$ref = q(word);

Upvotes: 4

Related Questions