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 +
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With