[Tutor] quick speed question
Dave Angel
davea at ieee.org
Thu Sep 16 10:46:59 CEST 2010
On 2:59 PM, C.T. Matsumoto wrote:
> Hello Tutors,
>
> I was just wondering if you have a dictionary key is it faster to do:
>
> if dict['key'] == 'foo':
> ...
>
> or is this faster:
>
> if 'foo' in dict['key']:
> ...
>
> Or is there any difference and I'm chasing ghosts?
>
> Thanks,
>
> T
dict is not a good name for a dictionary, since it's a built-in name.
But ignoring that,
The two lines you show do different things
Both of them look up a single item in the dictionary, so that part takes
the same time. But then the first compares the resulting string to
exactly 'foo', while the second searches in the string to see if 'foo'
is a substring.
If you need one of them, the other will get the wrong answer. So
knowing that the first is faster is irrelevant.
DaveA
More information about the Tutor
mailing list