As the others have identified, x creates the scalars nice and efficiently, and then throws that away by copying it into the scalar, rather than pointing the scalar at the string it created :(

If you're on a version of Perl that supports memory files, here's a technique I use for allocating big strings.

It's more efficent than x in two ways:

  1. No duplication.
  2. No initialisation.

Of course, the latter may be a downside too.

#! perl -slw use strict; our $SIZE ||= 10_000_000; sub allocBig { local $/; open my $memFile, '>', \$_[ 0 ] or die $!; seek $memFile, $_[ 1 ], 0; print $memFile chr(0); return; } printf 'Check '; <STDIN>; my $bigScalar; allocBig $bigScalar, $SIZE; print length $bigScalar; printf 'Check '; <STDIN>; __END__ P:\test>414880 Check 1660/528k 10000002 Check 1888/10376k P:\test>414880 -SIZE=200000000 Check 1664/528k 200000002 Check 1892/196104k

Of course, then you face the problem of using it without it getting freed and replaced, but that's what substr and lvalue refs are for :)


Examine what is said, not who speaks.        The end of an era!
"But you should never overestimate the ingenuity of the sceptics to come up with a counter-argument." -Myles Allen
"Think for yourself!" - Abigail        "Time is a poor substitute for thought"--theorbtwo         "Efficiency is intelligent laziness." -David Dunham
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

In reply to Re: Possibly silly perl memory allocation question, duplicating scalars by BrowserUk
in thread Possibly silly perl memory allocation question, duplicating scalars by BUU

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.