#TIL #Python

$ python -m timeit -n 100 -s "d = {}" "d.update((i, i) for i in range(10000))"
100 loops, best of 5: 1.15 msec per loop

$ python -m timeit -n 100 -s "d = {}" "d.update({i: i for i in range(10000)})"
100 loops, best of 5: 861 usec per loop

@cedrickrier So in the first one you're feeding update a generator, but in the second one you're feeding it another dictionary? If so, it makes sense that the second one takes much longer, as you're building the entire dictionary twice.

@peterdrake Except that it is the opposite. The dictionary way is faster.
I suspect that the creation of the 10k tuples is slower than the creation of the corresponding dictionary.

Follow

@cedrickrier Oh, MICROseconds -- I missed that!

Interesting. I'd think the dictionary would need to create all of the tuples (or some equivalent key-value pairs) anyway. Maybe the behind-the-scenes data structure storing a pair in a dictionary is more efficient than a tuple, because it knows it contains exactly two items.

Sign in to participate in the conversation
CleverLibre Social

CleverLibre Social is an inclusive social instance for open discussion, learning, and community.
All cultures welcome.
Hate speech and harassment strictly forbidden.