On Sun, Jul 19, 2020 at 7:20 AM Marco Sulla <marco.sulla.pyt...@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