del可以使Python更快吗?

时间:2018-11-27 00:40:17

标签: python

作为一名程序员,我通常会尽量避免使用del语句,因为这通常是Python程序不需要的额外复杂性。但是,在浏览标准库(threadingos等...)和伪标准库(numpyscipy等)时,我看到它使用了非零的次数,并且我想更好地了解何时{/ {1}}语句不合适。

特别是,我对Python del语句与Python程序的效率之间的关系感到好奇。在我看来,del可以通过减少筛选所需的混乱查找指令的数量来帮助程序更快地运行。但是,我也可以看到一个世界,额外的指令占用了比节省的时间更多的时间。

我的问题是:是否有人有有趣的代码段来说明del会大大改变程序速度的情况?我对del提高程序执行速度的情况最感兴趣,尽管del确实会造成伤害的非平凡的情况也很有趣。

2 个答案:

答案 0 :(得分:2)

The main reason that standard Python libraries use del is not for speed but for namespace decluttering ("avoiding namespace pollution" is another term I believe I have seen for this). As user2357112 noted in a comment, it can also be used to break a traceback cycle.

Let's take a concrete example: line 58 of types.py in the cpython implementation reads:

del sys, _f, _g, _C, _c, # Not for export

If we look above, we find:

def _f(): pass
FunctionType = type(_f)
LambdaType = type(lambda: None)         # Same as FunctionType
CodeType = type(_f.__code__)
MappingProxyType = type(type.__dict__)
SimpleNamespace = type(sys.implementation)

def _g():
    yield 1
GeneratorType = type(_g())

_f and _g are two of the names being deled; as the comment says, they are "not for export".1

You might think this is covered via:

__all__ = [n for n in globals() if n[:1] != '_']

(which is near the end of that same file), but as What's the python __all__ module level variable for? (and the linked Can someone explain __all__ in Python?) note, these affect the names exported via from types import *, rather than what's visible via import types; dir(types).

It's not necessary to clean up your module namespace, but doing so prevents people from sneaking into it and using undefined items. So it's good for a couple of purposes.


1Looks like someone forgot to update this to include _ag. _GeneratorWrapper is harder to hide, unfortunately.

答案 1 :(得分:0)

Specifically, I'm curious about the relationship between the Python del statement and the efficiency of a Python program.

As far as performance is concerned, del (excluding index deletion like del x[i]) is primarily useful for GC purposes. If you have a variable pointing to some large object that is no longer needed, deling that variable will (assuming there are no other references to it) deallocate that object (with CPython this happens immediately, as it uses reference counting). This could make the program faster if you'd otherwise be filling your RAM/caches; only way to know is to actually benchmark it.

It seems to me that del might help a program run faster by reducing the amount of clutter lookup instructions need to sift through.

Unless you're using thousands of variables (which you shouldn't be), it's exceedingly unlikely that removing variables using del will make any noticeable difference in performance.