Which is faster? (if not b in m) or (if m.count(b) > 0)
Jean-Paul Calderone
exarkun at divmod.com
Sun Feb 19 19:42:09 EST 2006
On Mon, 20 Feb 2006 10:08:48 +1100, "Delaney, Timothy \(Tim\)" <tdelaney at avaya.com> wrote:
>Farel wrote:
>
>> Tim, Are you saying that:
>> not (b in m)
>> is faster than:
>> b not in m
>
>On the contrary. `not (b in m)` requires negating the result of `b in m`
>(via an additional bytecode operation). `b not in m` doesn't. However,
>the difference in performance is minimal, as testing using the timeit
>module will show you.
Not since Python 2.4:
>>> dis.dis(lambda: x not in y)
1 0 LOAD_GLOBAL 0 (x)
3 LOAD_GLOBAL 1 (y)
6 COMPARE_OP 7 (not in)
9 RETURN_VALUE
>>> dis.dis(lambda: not (x in y))
1 0 LOAD_GLOBAL 0 (x)
3 LOAD_GLOBAL 1 (y)
6 COMPARE_OP 7 (not in)
9 RETURN_VALUE
>>>
>
>The important difference is the improvement in clarity. There is no
>possibility for misinterpretation as to the meaning of `b not in m`,
>whereas with the original `not b in m` I had to actually go check the
>precedence rules to be sure what would happen. Adding the parentheses
>makes it clear, but doesn't read as well as using the `not in` operator.
>
>As others have said, if you really care about the performance of
>something, the timeit module is your friend. Discussions about *why* you
>get certain performance results are then useful.
But this stuff is all still true :)
Jean-Paul
More information about the Python-list
mailing list