Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster to assign dictionary value to variable, or continually access?

I have a dictionary such as:

d = {'a':'a-val', 'b':'b-val', 'c':'c-long-val'*1000}

And I need to repeatedly access d['c'] as in:

print('value of c is', d['c'])
x_queue.put(d['c'])
some_function(d['c'])

But I'm wondering if it would be faster to assign d['c'] to a variable and use it each time:

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)

My hunch is it may depend on

  • number of elements in d (finding key is more costly with bigger d)
  • size of d['c'] (assignment is more costly with bigger d['c'])

But I'm really not sure if one of those options (or another?) is faster or more pythonic.

like image 574
Dan Pittsley Avatar asked May 03 '26 20:05

Dan Pittsley


1 Answers

Although accessing a dict value by key has an average time complexity of O(1), it has a worst-case time complexity of O(n) after incurring the overhead of calculating the hash value of the key. A variable assignment and the retrieval of its value on the other hand, take very minimal, constant time, so avoid re-evaluating a dict value by key whenever possible.

like image 50
blhsing Avatar answered May 05 '26 11:05

blhsing