more efficient?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Dec 22 01:59:56 EST 2009


En Tue, 22 Dec 2009 03:13:38 -0300, Zubin Mithra <zubin.mithra at gmail.com>  
escribió:

> I have the following two implementation techniques in mind.
>
> def myfunc(mystring):
>     check = "hello, there " + mystring + "!!!"
>     print check
>
>
> OR
> structure = ["hello, there",,"!!!"]
> def myfunc(mystring):
>     structure[2] = mystring
>     output = ''.join(mystring)
>
> i heard that string concatenation is very slow in python; so should i
> go for the second approach? could someone tell me why? Would there be
> another 'best-practice-style'?

THIS is slow for large enough values of len(items):

def concat(items):
   result = ''
   for item in items:
      result += item
   return result

because at each stage it has to create a new string, bigger than the  
previous one; it's an n**2 process.
Concatenating just three strings as in your example is fast. The time  
spent in dereferencing the "structure" name, indexing into it, creating  
the join bound method, iterating, etc. is way longer than the inefficiency  
of using + in this case. Anyway, don't blindly trust me, measure it:

> python -m timeit -s "def one(x): return 'hello, there '+x+'!!!'"  
> "one('gabriel')"
100000 loops, best of 3: 7.9 usec per loop

> python -m timeit -s "lst=['hello, there ','','!!!']" -s "def two(x):  
> lst[1]=x; return ''.joi
n(lst)" "two('gabriel')"
100000 loops, best of 3: 12.4 usec per loop

> python -m timeit -s "def three(x): return ''.join(('hello, there  
> ',x,'!!!'))" "three('gabr
iel')"
100000 loops, best of 3: 11.9 usec per loop

Anyway, usually, showing a message isn't critical and one doesn't care how  
fast it goes, so I'd use this version which is a lot more readable (and  
easier to localize, BTW):

def myfunc(mystring):
   check = "hello, there {0}!!!".format(mystring)
   print check

-- 
Gabriel Genellina




More information about the Python-list mailing list