小编Dan*_*ley的帖子

将字典值分配给变量或连续访问更快?

我有一本字典,例如:

d = {'a':'a-val', 'b':'b-val', 'c':'c-long-val'*1000}
Run Code Online (Sandbox Code Playgroud)

我需要重复访问,d['c']如下所示:

print('value of c is', d['c'])
x_queue.put(d['c'])
some_function(d['c'])
Run Code Online (Sandbox Code Playgroud)

d['c']但我想知道分配给变量并每次使用它是否会更快:

c_value = d['c']` # is this assignment "worth it"?
print('value of c is', c_value)
x_queue.put(c_value)
some_function(c_value)
Run Code Online (Sandbox Code Playgroud)

我的预感是这可能取决于

  • 中的元素数量d(查找键值越大,成本越高)d)
  • 的大小d['c'](分配的成本越大d['c']

但我真的不确定这些选项之一(或另一个?)是否更快更Pythonic

python performance dictionary python-3.x

6
推荐指数
1
解决办法
1895
查看次数

标签 统计

dictionary ×1

performance ×1

python ×1

python-3.x ×1