gpt4 book ai didi

python - dict.__setitem__(key, x) 是否比 dict[key] = x 慢(或快),为什么?

转载 作者:行者123 更新时间:2023-12-03 21:05:11 25 4
gpt4 key购买 nike

我发现了一些奇怪的东西。
我定义了两个测试函数:

def with_brackets(n=10000):
d = dict()
for i in range(n):
d["hello"] = i

def with_setitem(n=10000):
d = dict()
st = d.__setitem__
for i in range(n):
st("hello", i)

人们会期望这两个函数的执行速度大致相同。然而:
>>> timeit(with_brackets, number=1000)
0.6558860000222921

>>> timeit(with_setitem, number=1000)
0.9857697170227766
我可能错过了一些东西,但似乎 setitem 的长度几乎是原来的两倍,我真的不明白为什么。 dict[key] = x 不是应该调用 __setitem__ 吗?
(使用 CPython 3.9)
编辑:使用 timeit 而不是 time

最佳答案

Isn't dict[key] = x supposed to call __setitem__?


严格来说,没有。通过 dis.dis 运行您的两个功能,我们得到(我只包括 for 循环):
>>> dis.dis(with_brackets)
...
>> 22 FOR_ITER 12 (to 36)
24 STORE_FAST 3 (i)

5 26 LOAD_FAST 0 (n)
28 LOAD_FAST 1 (d)
30 LOAD_CONST 1 ('hello')
32 STORE_SUBSCR
34 JUMP_ABSOLUTE 22
...
对比
>>> dis.dis(with_setitem)
...
>> 28 FOR_ITER 14 (to 44)
30 STORE_FAST 4 (i)

6 32 LOAD_FAST 2 (setitem)
34 LOAD_CONST 1 ('hello')
36 LOAD_FAST 0 (n)
38 CALL_FUNCTION 2
40 POP_TOP
42 JUMP_ABSOLUTE 28
...
__setitem__的用法涉及函数调用(参见 CALL_FUNCTIONPOP_TOP 的用法,而不仅仅是 STORE_SUBSCR - 这是引擎盖下的区别)和 function calls do add some amount of overhead ,因此使用括号访问器会导致更优化的操作码。

关于python - dict.__setitem__(key, x) 是否比 dict[key] = x 慢(或快),为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67596596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com