[Tutor] Performance difference, ``in'' vs ``has_key()''

R. Alan Monroe amonroe at columbus.rr.com
Sun Jul 17 21:15:42 CEST 2005


> Is there any significant performance difference between the
> tests, ``key in dictionary'' and ``dictionary.has_key(key)''?
> I would prefer using the ``key in'' because it's a bit easier to
> type, and can also be used with lists in addition to dictionaries.

Dunno about speed, but they do disassemble slightly differently:


>>> import dis
>>> a={1:2, 3:4}
>>> def x():
...     if 3 in a:
...             print "3 in"
...
>>> def y():
...     if a.has_key(3):
...             print "3 has"
...
>>> dis.dis(x)
  2           0 LOAD_CONST               1 (3)
              3 LOAD_GLOBAL              0 (a)
              6 COMPARE_OP               6 (in)
              9 JUMP_IF_FALSE            9 (to 21)
             12 POP_TOP

  3          13 LOAD_CONST               2 ('3 in')
             16 PRINT_ITEM
             17 PRINT_NEWLINE
             18 JUMP_FORWARD             1 (to 22)
        >>   21 POP_TOP
        >>   22 LOAD_CONST               0 (None)
             25 RETURN_VALUE
>>> dis.dis(y)
  2           0 LOAD_GLOBAL              0 (a)
              3 LOAD_ATTR                1 (has_key)
              6 LOAD_CONST               1 (3)
              9 CALL_FUNCTION            1
             12 JUMP_IF_FALSE            9 (to 24)
             15 POP_TOP

  3          16 LOAD_CONST               2 ('3 has')
             19 PRINT_ITEM
             20 PRINT_NEWLINE
             21 JUMP_FORWARD             1 (to 25)
        >>   24 POP_TOP
        >>   25 LOAD_CONST               0 (None)
             28 RETURN_VALUE


Alan



More information about the Tutor mailing list