my $Data1 = ReadFile($filename1);
my $Data2 = ReadFile($filename2);
my $Data3 = ReadFile($filename3);
my $OutputData = '';
$OutputData .= ......
undef $Data2;
my $Data4 = ReadFile($filename4);
...
CreateFile($output_filename, \$OutputData); # Pass by ref to prevent double copy
exit;
Undef would successfully unload it from the memory. But will it cause large memory blocks to be moved around since it's in the middle? How does Perl deal with memory fragmentation? What happens when there's a memory hole, and I create a new string and slurp the file using sysread() to fill the string. And I imagine that as the string grows, it outgrows that hole and has to be placed into another location. Right? I'm trying to understand what's going on in the background so I can design my code to be efficient.
- I don't want to end up with creating double copies of the same data in memory.
- I don't want to hog memory by not releasing it when I'm done with it.
- I don't want to waste resources unnecessarily.
I would appreciate any helpful advice!!
The rest of the code (which is irrelevant):
# Usage: STRING = ReadFile(FILENAME, START, LENGTH) - Reads an entire file or part of a file in binary mode. Returns the file contents as a string. An optional second argument will move the file pointer before reading, and an optional third argument limits the number of bytes to read.
sub ReadFile {my$F=defined$_[0]?$_[0]:'';$F=~tr#><*%$?\r\n\"\0|##d;-e$F||return'';-f$F||return'';my$S=-s$F;$S||return'';my$L=defined$_2?$_2:$S;$L>0||return'';local*H;sysopen(H,$F,0)||return'';binmode H;my$P=defined$_1?$_1:0;$P>=0or $P=0;$P<$S||return'';$P<1||sysseek(H,$P,0);my$D='';sysread(H,$D,$L);close H;return$D;}
In reply to Memory efficient design by harangzsolt33
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |