in reply to Re^2: how apply large memory with perl?
in thread how apply large memory with perl?
I don't know internal details of .. op and $#, but what makes so big difference?
When you use the range operator outside of a for loop, Perl creates that list on one of its internal stacks first. This requires ~650MB, and is best illustrated by creating that mythically non-existant "list in a scalar context":
C:\test>perl -E"scalar( ()=1..9e6 ); say grep /$$/,`tasklist`" perl.exe 2548 Console 1 650 +,108 K
Now we've got the list, it need to be copied to the array, which takes the other ~300MB:
C:\test>perl -E"@a=1..9e6; say grep /$$/,`tasklist`" perl.exe 2596 Console 1 937 +,388 K
When you use the range operator in the context of a for statement; it acts as an iterator, thus completely avoiding the creation of the stack-based list:
C:\test>perl -E"1 for 1..9e6; say grep /$$/,`tasklist`" perl.exe 4112 Console 1 4 +,776 K
If we just assigned the values to the array one at a time, the array would have to keep doubling in size each time it filled; in order to accommodate new values, resulting in the memory from previous resizings freed to the heap, but still needed at one instance in time and an overall memory usage of 400MB:
C:\test>perl -E"$a[$_-1]=$_ for 1..9e6; say grep /$$/,`tasklist`" perl.exe 2800 Console 1 402 +,312 K
By pre-sizing the array to its final size we save those intermediate resizings and another 100+MB:
C:\test>perl -wE"$#a=9e6; $a[$_-1]=$_ for 1..9e6; say grep /$$/,`taskl +ist`" perl.exe 4880 Console 1 292 +,196 K
Simple steps with big gains.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: how apply large memory with perl?
by aaron_baugher (Curate) on Aug 09, 2012 at 13:35 UTC | |
by BrowserUk (Patriarch) on Aug 09, 2012 at 14:41 UTC |