best way to replace first word in string?

Ron Adam rrr at ronadam.com
Sun Oct 23 01:27:44 EDT 2005


bonono at gmail.com wrote:

> interesting. seems that "if ' ' in source:" is a highly optimized code
> as it is even faster than "if str.find(' ') != -1:' when I assume they
> end up in the same C loops ?


The 'in' version doesn't call a function and has a simpler compare.  I 
would think both of those results in it being somewhat faster if it 
indeed calls the same C loop.


 >>> import dis
 >>> def foo(a):
...   if ' ' in a:
...      pass
...
 >>> dis.dis(foo)
   2           0 LOAD_CONST               1 (' ')
               3 LOAD_FAST                0 (a)
               6 COMPARE_OP               6 (in)
               9 JUMP_IF_FALSE            4 (to 16)
              12 POP_TOP

   3          13 JUMP_FORWARD             1 (to 17)
         >>   16 POP_TOP
         >>   17 LOAD_CONST               0 (None)
              20 RETURN_VALUE
 >>>
 >>> def bar(a):
...   if str.find(' ') != -1:
...      pass
...
 >>> dis.dis(bar)
   2           0 LOAD_GLOBAL              0 (str)
               3 LOAD_ATTR                1 (find)
               6 LOAD_CONST               1 (' ')
               9 CALL_FUNCTION            1
              12 LOAD_CONST               2 (-1)
              15 COMPARE_OP               3 (!=)
              18 JUMP_IF_FALSE            4 (to 25)
              21 POP_TOP

   3          22 JUMP_FORWARD             1 (to 26)
         >>   25 POP_TOP
         >>   26 LOAD_CONST               0 (None)
              29 RETURN_VALUE
 >>>



More information about the Python-list mailing list