So for example, $x = 'a' x 10 gets converted into $x = 'aaaaaaaaaa' at compile time, and a 10-byte block of memory will have been allocated at compile-time.
At run time, that constant string is retrieved, and its value assigned to $x. At its most simple, $x gets a 10-byte buffer allocated, then the 10 bytes from the constant string "aaaaaaaaaa" are copied into $x's string buffer. So the program allocates 20 bytes in total. If repeated multiple times, e.g.
Then on subsequent calls, the buffer for $x is re-used, so the total memory usage for the program doesn't increase beyond the 2 x 10 bytes already allocated.sub foo { my $x = 'x' x 10; ... }
However, perl has a scheme called Copy-On_Write (COW). Often when a string is copied from one location to another, a second buffer isn't allocated; instead the string buffer is shared between the two scalars. Later, if one of the scalars is modified, the buffer is duplicated and the two scalars become independent of each other. COW normally works fine for constant assignments, but for some reason it isn't working when the constant is the result of compile-time constant-folding:
This is probably a bug.$ perl -MDevel::Peek -e'my $x = "aaaaaaaaaa"; Dump $x' 2>&1 | grep COW FLAGS = (POK,IsCOW,pPOK) COW_REFCNT = 1 $ perl -MDevel::Peek -e'my $x = "aaaaa" . "aaaaa"; Dump $x' 2>&1 | gre +p COW $ perl -MDevel::Peek -e'my $x = "a" x 10; Dump $x' 2>&1 | grep COW
Dave.
In reply to Re^5: Memory usage double expected -- further questions (deparse)
by dave_the_m
in thread Memory usage double expected
by sectokia
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |