$ x = undef和undef $ x之间的行为差​​异

Ani*_*han 2 perl garbage-collection

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

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

ike*_*ami 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
Run Code Online (Sandbox Code Playgroud)

  • 要清楚,既不是`undef $ x;也不是`$ x = undef;`自由`$ x`本身. (2认同)