<div dir="ltr">So this pattern is a valid python optimization? Funky...<div><br></div><div>Sadly, there's no way around it unless the interpreter somehow did it magically for you.<br><br><div class="gmail_quote">On Sun, Sep 13, 2009 at 10:37 PM, Raymond Hettinger <span dir="ltr"><<a href="mailto:python@rcn.com">python@rcn.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;"><div class="im"><br>
On Sep 13, 2009, at 11:10 AM, Gerald Britton wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
 Here are some results:<br>
<br>
$ python -m timeit -n 1000000  -s 'with open("/usr/share/dict/words")<br>
as f: s = set(w.strip("\n") for w in f)'  's.add("mother")'<br>
1000000 loops, best of 3: 0.292 usec per loop<br>
<br>
britton@TheBrittons:~$ python -m timeit -n 1000000  -s 'with<br>
open("/usr/share/dict/words") as f: s = set(w.strip("\n") for w in f)'<br>
'if "mother" not in s:s.add("mother")'<br>
1000000 loops, best of 3: 0.185 usec per loop<br>
<br>
the second example beats the first by about 36%<br>
<br>
Is the timing difference just the cost of the method lookup for s.add,<br>
or is something else happening that I'm not seeing?<br>
</blockquote>
<br></div>
It is the something else you're not seeing ;-)<br>
<br>
On the first pass of the 1000000 loops, "mother" gets added.<br>
On the remaining passes the 'if "mother" not in set' test fails<br>
and the set.add() never gets executed.  That latter operation<br>
is a bit more expensive than the contains-test because it<br>
includes the time to lookup and bind the add method.<br><font color="#888888">
<br>
<br>
Raymond</font><div><div></div><div class="h5"><br>
<br>
_______________________________________________<br>
Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org" target="_blank">Python-ideas@python.org</a><br>
<a href="http://mail.python.org/mailman/listinfo/python-ideas" target="_blank">http://mail.python.org/mailman/listinfo/python-ideas</a><br>
</div></div></blockquote></div><br></div></div>