问题描述
想象一下一个假设的情况,其中一个函数返回两个值:一个您不感兴趣的庞大数据集和一个所需的小摘要.如果您的脚本(非交互式外壳程序)具有类似
Imagine a hypothetical situation where a function returns two values: a huge dataset you are not interested in and a small summary you want. If your script (not interactive shell) has code like
_, the_answer = deep_thought.ask(the_ultimate_question)
,垃圾回收器将_
与其他任何名称区别对待,并比使用pp更快地释放可用内存
, will the garbage collector treat _
any different than any other name and free memory any quicker than with
mostly_harmless, the_answer = deep_thought.ask(the_ultimate_question)
假设mostly_harmless
将永远不会被使用.起初我以为不会,但是在阅读以下内容之后: Python垃圾回收和解释器环境中的_下划线我开始怀疑.我希望这里的人会比我更快地找到答案.
assuming mostly_harmless
will never by used. At first I assumed it wouldn't but after reading this: python garbage collection and _ underscore in interpreter environment I started having doubts. I hope someone here will know the answer or find it quicker than me.
此外,对于奖励积分,它如何与绩效进行比较
Also, for bonus points, how does it compare performance-wise with
the_answer = deep_thought.ask(the_ultimate_question)[1]
?
推荐答案
注意:以下内容适用于CPython(标准解释器)
Note: the following applies to CPython (the standard interpreter)
要首先了解垃圾收集器,您必须了解name
是什么,object
是什么以及对象的引用计数是
To understand the garbage collector first you must understand what a name
is, what an object
is and what an object's reference count is
执行以下功能
def foo():
_ = {}
函数执行时,函数的本地字典和CPython内部保存的全局对象看起来像这样. (这是一个过于简化的解释)
When the function is being executed the function's locals dictionary and the global objects internally held by CPython look something like this. (This is an over simplified explanation)
-------------------- ------------------------
| name | object_id | | id | reference_count |
-------------------- ------------------------
| _ | 1 | | 1 | 1 |
该函数完成后,其本地字典会被破坏,所有引用的对象的reference_count都会减少
When the function is complete it's locals dictionary is destroyed and any objects that were referenced have their reference_count decremented
------------------------
| id | reference_count |
------------------------
| 1 | 0 |
垃圾收集器最终将删除ID为1
的对象,因为该对象不再具有任何引用,引用的名称(变量名称)无关紧要.
The garbage collector will eventually delete the object with id 1
as it no longer has any references to it, the names of the references (variable names) do not matter.
该变量可以被命名为任何东西,对于垃圾收集器而言,仅是对象的引用计数无关紧要
The variable could have been named anything and it wouldn't matter to the garbage collector only the object's reference count
这篇关于Python垃圾收集器的行为是否带有_单个下划线变量名,是否真的不同?多变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!