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

Marco Sulla Marco.Sulla.Python at gmail.com
Sat Jul 18 18:55:50 EDT 2020


... oh my ... Sure, thank you.
Thinking positive, I wasted a lot of hours, but I discovered
timeit.Timer.autorange


On Sat, 18 Jul 2020 at 23:30, Chris Angelico <rosuav at gmail.com> wrote:

> 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
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list