2

undef $x不同于$x = undef. 我的印象是两者都会触发垃圾收集和释放内存,但似乎$x = undef没有这样做。

这是语言错误吗?在做$x = undef时,它不应该释放内存吗?

4

1 回答 1

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
于 2013-03-12T19:31:51.027 回答