undef $x
is different from $x = undef
。我的印象是两者都会触发垃圾收集和释放内存,但似乎$x = undef
没有这样做。
这是一个语言错误吗?在做$x = undef
时,它不应该释放内存吗?
答案 0 :(得分:7)
不,不。 Perl倾向于通过不再释放你可能需要的内存而超过内存使用速度。如果要取消分配字符串缓冲区,请使用undef $x;
。
$ perl -MDevel::Peek -e'
Dump($x);
$x='abc'; Dump($x);
$x=undef; Dump($x);
undef $x; Dump($x);
'
SV = NULL(0x0) at 0x1c39284 <-- No body allocated
REFCNT = 1
FLAGS = () <-- Undefined
SV = PV(0x3e8d54) at 0x1c39284 <-- PV body allocated
REFCNT = 1
FLAGS = (POK,pPOK) <-- Contains a string
PV = 0x3eae7c "abc"\0
CUR = 3
LEN = 12
SV = PV(0x3e8d54) at 0x1c39284 <-- PV body allocated
REFCNT = 1
FLAGS = () <-- Undefined
PV = 0x3eae7c "abc"\0 <-- Currently unused string buffer
CUR = 3
LEN = 12
SV = PV(0x3e8d54) at 0x1c39284 <-- PV body allocated
REFCNT = 1
FLAGS = () <-- Undefined
PV = 0 <-- No string buffer allocated