Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is %s faster than + for python string concatentation

Understanding that using the str.join operator is the 'chosen' way to concatenate strings in python, I was wandering where in the pecking order operations of the type:

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

would fit. Are they faster or slower than using +?

like image 974
probably at the beach Avatar asked Dec 21 '22 09:12

probably at the beach


1 Answers

Let's 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
like image 70
Blender Avatar answered Jan 06 '23 02:01

Blender