Iterating over dict is slower than iterating over iter(dict)?

Chris Angelico rosuav at gmail.com
Sat Jul 18 17:28:38 EDT 2020


On Sun, Jul 19, 2020 at 7:20 AM Marco Sulla
<Marco.Sulla.Python at gmail.com> wrote:
>
> I noticed that iterating over a dictionary seems quite slower than creating
> an iterator and iterating over it. Maybe I miss something?

Welcome to microbenchmarks, where the tiniest change suddenly makes
the entire benchmark meaningless :)

> benchmarks = (
>     {"name": "for x in dict", "stmt": "for x in it: pass", "setup": """
> o = {k:k for k in range($size)}
> it = o
> """},
>     {"name": "for x in iter(dict)", "stmt": "for x in it: pass", "setup":
> """
> o = {k:k for k in range($size)}
> it = iter(o)
> """},
>     {"name": "iter(dict)", "stmt": "iter(o)", "setup": """
> o = {k:k for k in range($size)}
> """},
> )

You're creating an iterator once and then iterating over it lots of
times. In other words, after the first timing test, all the rest are
iterating over an empty collection. Unsurprisingly, that's faster than
actually looping :)

ChrisA


More information about the Python-list mailing list