python - 为什么从 dict.keys() 初始化 Set 比使用 set.add() 更快?
问题描述
代码
total_exc_time = 0
for _ in range(10):
start = time.time()
set_a = set()
dict_a = dict()
add = set_a.add
for index in range(1000000):
dict_a[index] = index
add(index)
total_exc_time += ((time.time() - start) * 1000)
total_exc_time = 0
for _ in range(10):
start = time.time()
dict_a = dict()
for index in range(1000000):
dict_a[index] = index
set_a = set(dict_a.keys())
total_exc_time += ((time.time() - start) * 1000)
结果
332.3066234588623 ms
283.2982540130615 ms
第一个代码的时间复杂度不是 O(n),后面的代码是 O(n) 的 2 倍吗?
解决方案
它们是等价的。这里的繁重工作是计算密钥哈希。在这两种情况下,它都会发生两次:添加到字典,然后添加到集合。其他程序应该很轻。您可以使用调试器显示 C 调用以进行验证。
除了 Carcigenicate 提到的函数调用开销之外,内存管理也可能发挥作用。如果集合知道长度,它可能会避免在预定义空间不够时复制数据。
推荐阅读
- react-native - 如何在反应本机应用程序中集成ckeditor
- flutter - 如何使文本动态调整自身大小以适应容器
- gcloud - 政策报告,用于查看帐户在 GCloud 上可以访问的所有资源的摘要
- pyspark - 使用 pyspark 估算负值的高效代码
- r - 在 r 中使用多个条件将控件与案例匹配
- python - 试图计算算术中位数
- mysql - 如何在连接的同一查询中显示前 5 名和后 5 名?
- python - python:当最小元素的数量大于1时,列表中的第二个最小值
- php - 如何在 https laravel 中运行 URL 以链接 css 和 js
- macos - SwiftUI:添加项目会在 NavigationView 列表中创建间隙