小编Pho*_*bia的帖子

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

我发现了一些奇怪的东西。

我定义了两个测试函数:

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)

Run Code Online (Sandbox Code Playgroud)

人们会期望这两个函数的执行速度大致相同。然而:

>>> timeit(with_brackets, number=1000)
0.6558860000222921

>>> timeit(with_setitem, number=1000)
0.9857697170227766
Run Code Online (Sandbox Code Playgroud)

我可能错过了一些东西,但似乎 setitem 的长度几乎是原来的两倍,我真的不明白为什么。dict[key] = x 不是应该调用 __setitem__ 吗?

(使用 CPython 3.9)

编辑:使用 timeit 而不是 time

python performance dictionary

4
推荐指数
1
解决办法
45
查看次数

标签 统计

dictionary ×1

performance ×1

python ×1