(Python3)是否多次访问字典或引用项目的值更好?

问题描述 投票:0回答:1

例如:

if(self._ConnectGenes[innov_num].is_enabled() and self._ConnectGenes[innov_num].is_computed()==False):
     self._NodeGenes[self._ConnectGenes[innov_num]._Out].value += self._NodeGenes[next] * self._ConnectGenes[innov_num]._Weight
     self._ConnectGenes[innov_num].set_computed(True)
     queue.append(self._ConnectGenes[innov_num]._Out) #Append the next skirt to the graph

我们在这里可以访问字典self._ConnectGenes,并且该项目存储在密钥中self._ConnectGenes [innov_num]

我想知道,如果我们改为引用该项目会更好,例如

genome = self._ConnectGenes[innov_num]
if(genome.is_enabled() and genome.is_computed()==False):
     genome._Out].value += self._NodeGenes[next] * genome._Weight
     genome.set_computed(True)
     queue.append(genome._Out) #Append the next skirt to the graph

会节省一些性能吗?由于这段代码将被调用多次。

python performance dictionary reference access
1个回答
0
投票

访问字典时,每次都会产生哈希/查找开销。如果要在同一代码块中多次使用同一键,则重复查找该键会浪费很多时间。将结果存储在变量中将更快,更干净。

© www.soinside.com 2019 - 2024. All rights reserved.