Is% s faster than + for python string concatenation

Understanding that using the str.join operator is the "chosen" way to concatenate strings in python, I wandered where in a hierarchical order operations like:

"%s %s" % (first_name, last_name) 

will do. Are they faster or slower than using + ?

+4
source share
2 answers

We will see:

 >>> first_name = 'Test' >>> last_name = 'Name' >>> %timeit "%s %s" % (first_name, last_name) 10000000 loops, best of 3: 168 ns per loop >>> %timeit ' '.join((first_name, last_name)) 10000000 loops, best of 3: 157 ns per loop >>> %timeit first_name + ' ' + last_name 10000000 loops, best of 3: 103 ns per loop 

And if you cache the tuple:

 >>> name_tuple = (first_name, last_name) >>> %timeit "%s %s" % name_tuple 10000000 loops, best of 3: 125 ns per loop >>> %timeit ' '.join(name_tuple) 10000000 loops, best of 3: 114 ns per loop 
+6
source

Answer: No.

enter image description here

 In [1]: tup = 'hello', 'world' In [2]: timeit 'hello' + 'world' 10000000 loops, best of 3: 20.2 ns per loop In [3]: timeit tup[0] + tup[1] 10000000 loops, best of 3: 129 ns per loop In [4]: timeit '{}{}'.format('hello', 'world') 1000000 loops, best of 3: 285 ns per loop In [5]: timeit '{}{}'.format(*tup) 1000000 loops, best of 3: 281 ns per loop In [6]: timeit '%s%s' % ('hello', 'world') 10000000 loops, best of 3: 122 ns per loop In [7]: timeit '%s%s' % tup 10000000 loops, best of 3: 135 ns per loop In [8]: timeit ''.join(['hello', 'world']) 1000000 loops, best of 3: 210 ns per loop In [9]: timeit ''.join(tup) 10000000 loops, best of 3: 121 ns per loop 
+5
source

All Articles