PEP 380提到可以在Python中优化yield from expr
语法。你知道吗
Using a specialised syntax opens up possibilities for optimisation when there is a long chain of generators. Such chains can arise, for instance, when recursively traversing a tree structure. The overhead of passing
__next__()
calls and yielded values down and up the chain can cause what ought to be an O(n) operation to become, in the worst case, O(n**2).A possible strategy is to add a slot to generator objects to hold a generator being delegated to. When a
__next__()
orsend()
call is made on the generator, this slot is checked first, and if it is nonempty, the generator that it references is resumed instead. If it raisesStopIteration
, the slot is cleared and the main generator is resumed.This would reduce the delegation overhead to a chain of C function calls involving no Python code execution. A possible enhancement would be to traverse the whole chain of generators in a loop and directly resume the one at the end, although the handling of
StopIteration
is more complicated then.
CPython实现了这个优化吗?你知道吗
看起来不像。从python3.6开始,generator object structure没有建议的字段,} 操作码经过^{} /^{} 到^{} ,然后从那里到
yield from
通过一系列生成器的代码路径总是经历单独恢复其Python堆栈帧的过程。(此代码路径从^{PyEval_EvalFrameEx
再到链中下一个生成器的YIELD_FROM
)相关问题 更多 >
编程相关推荐