So precreate the string. Doing so doesn't cost a lot (assuming your sample represents your real code) so probably doesn't impact performance much for small numbers of iterations but, as you have discovered, provides a big win for large numbers of iterations.

If you really don't want to do that, you can get most of the benefit by using a piecemeal preallocate and copy technique:

use strict; use warnings; #number of items to pack my $iter = 1000000; my $string; my $startAlloc = 0; my $preAllocSize = $startAlloc; Time (); $$string = ''; #now lets create the data block... for my $count (1 .. $iter) { if ($preAllocSize && length ($$string) >= $preAllocSize) { $preAllocSize = length ($$string) * 2; my $newStr = 1 x $preAllocSize; $newStr = $$string; $string = \$newStr; } $$string .= 'x' x 20; } Time (); print "Finished with start alloc: $startAlloc\n"; print "Final string length: ", length ($$string); sub Time { my ($user, $system, $cuser, $csystem) = times; print "$user,$system\n"; }

for two different runs prints:

0.015,0 18.345,29.78 Finished with start alloc: 0 Final string length: 20000000 0.015,0 0.374,0.046 Finished with start alloc: 1 Final string length: 20000000

True laziness is hard work

In reply to Re: Memory allocation/performance issue for large strings (of binary data) under Windows. by GrandFather
in thread Memory allocation/performance issue for large strings (of binary data) under Windows. by Anonymous Monk

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.