[Tutor] quick speed question

Modulok modulok at gmail.com
Thu Sep 16 10:40:59 CEST 2010


This is faster:

    if dict['key'] == 'foo':
        pass

...But just slightly. (About 9% faster on my machine. This may differ
depending on the implementation, but I doubt it. See the 'timeit'
module.) Whether it's a big deal depends on what you're doing.
Accessing the dict - a million times - with either method took less
than a second. Visually, this makes more sense to me:

    if dict['key'] == 'foo':
        pass

Regardless, you should be aware that while they look similar, they
differ in their semantics:

    # Something to work with:
    dic = {'a': "Big", 'b': "Bigger"}

    # This is true:
    if dic['a'] == "Big":
        print True

    # And this is true:
    if "Big" in dic['a']:
        print True

    # But this is also true!
    if "Big" in dic['b']:
        print True

As far as speed is concerned: Don't worry about it unless has already
become a problem. Premature optimization wastes time you should be
spending solving the actual problem. For example, if you wrote an MP3
player that sorted playlists in 0.00001 seconds instead of 0.00002
seconds (100% faster!), but you wasted 3 days doing it - you haven't
accomplished much.

When you're done and you find you need a faster solution, optimize
your algorithms. If that still isn't enough, ask somebody smarter than
yourself to look at it. (This list is great for that!) If that too
fails, start think about writing a few critical bits in C, but only as
a last resort.

"We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil" -Donald knuth-

-Modulok-

On 9/16/10, C.T. Matsumoto <c.t.matsumoto at gmail.com> 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
> --
> C.T. Matsumoto
> Claes de Vrieselaan 60a III
> 3021 JR Rotterdam
> The Netherlands
>
> tel.: +31 (0)6 41 45 08 54
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list