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:
- No duplication.
- 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 :)
"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
|