Why can splitting one stream between two consumers increase memory use?

tee gives consumers independent cursors and buffers items that a slower cursor still needs.

Python example and interpretation

One reader can reach the third item while the other still sees the first. A prolonged gap can require buffering nearly the entire input.

from itertools import tee
a,b=tee(iter([10,20,30]))
[next(a),next(a),next(a),next(b)]

Result [10, 20, 30, 10]

中文

为什么把数据流分给两个消费者后内存仍会增长?

tee 为一个输入创建多个可独立前进的迭代器,并暂存落后消费者尚未读取的项目。

Python 算例与适用条件

第一路读到第三项时第二路仍可从第一项读起。若两路速度长时间相差悬殊,缓冲区可能接近整份数据。

from itertools import tee
a,b=tee(iter([10,20,30]))
[next(a),next(a),next(a),next(b)]

结果 [10, 20, 30, 10]

References / 参考来源

Keep reading / 继续阅读