Why is `{*l}` faster than `set(l)` - python sets (not really only for sets, for all sequences)(为什么 `{*l}` 比 `set(l)` 快 - python 集合(不仅适用于集合,适用于所有序列))
问题描述
所以这是我的时间安排:
So here is my timings:
>>> import timeit
>>> timeit.timeit(lambda: set(l))
0.7210583936611334
>>> timeit.timeit(lambda: {*l})
0.5386332845236943
为什么会这样,我的意见是平等的,但事实并非如此.
Why is that, my opinion would be equal but it's not.
所以从这个例子中解包很快,对吧?
So unpacking is fast from this example, right?
推荐答案
同理[]比 list() 快;解释器包括对使用专门代码路径的基于语法的操作的专门支持,而构造函数调用涉及:
For the same reason [] is faster than list(); the interpreter includes dedicated support for syntax based operations that uses specialized code paths, while constructor calls involve:
- 从内置范围加载构造函数(需要一对
dict查找,一个在全局范围内,另一个在内置范围内失败时) - 需要通过通用可调用调度机制和通用参数解析代码进行调度,所有这些都比将其所有参数作为 C 数组从堆栈中读取的单字节代码昂贵得多
- Loading the constructor from built-in scope (requires a pair of
dictlookups, one in global scope, then another in built-in scope when it fails) - Requires dispatch through generic callable dispatch mechanisms, and generic argument parsing code, all of which is far more expensive than a single byte code that reads all of its arguments off the stack as a C array
所有这些优点都与固定开销有关;两种方法的 big-O 相同,因此 {*range(10000)} 不会明显/可靠地比 set(range(10000)) 快,因为实际的构造工作远远超过了通过泛型调度加载和调用构造函数的开销.
All of these advantages relate to fixed overhead; the big-O of both approaches are the same, so {*range(10000)} won't be noticeably/reliably faster than set(range(10000)), because the actual construction work vastly outweighs the overhead of loading and calling the constructor via generic dispatch.
这篇关于为什么 `{*l}` 比 `set(l)` 快 - python 集合(不仅适用于集合,适用于所有序列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 `{*l}` 比 `set(l)` 快 - python 集合(不仅适用于集合,适用于所有序列)
基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
