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
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |