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 集合(不仅适用于集合,适用于所有序列)
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
