Trivial performance questions
Alex Martelli
aleax at aleax.it
Sat Oct 18 14:02:54 EDT 2003
Bryan wrote:
> > If you *get into the habit* of always checking with "if x is None:"
>> rather than "if x == None:" -- two equally readable constructs -- it
>> will cost you no increase in effort whatsoever to always use the
>> idiom you've gotten used to. So, whether the (tiny) extra speed and
>> readability are important or not, it's still a good habit to pick up.
> >
>> Alex
>>
>
> can you explain in more detail why "if x is None:" is better/faster than
> "if x == None:"? i guess i don't fully
> understand "is". my fingers always seem to want to type "if not x:", but
> that is probably worse still since it includes (), [], {}, '', False, None
If you WANT to include other false values, then of course "if not x:" is
just perfect. But with either 'is None' or '== None' you're checking
specifically for None -- quite different semantics.
"a is None" a bit more readable than "a == None" because it uses readable
words rather than punctuation. It's a bit faster, because 'is' gets the
id (machine addresses) of its operands and just compares them -- it looks
for IDENTITY, the SAME objects, as opposed to two separate objects which
happen to have the same value; '==' necessarily must do a bit more work,
because many objects can be equal without being the same object.
Alex
More information about the Python-list
mailing list