String concat vs Join

Posted by Afsal on 18-Mar-2022

Hi Pythonistas!

Today we are going to learn another performance improvement tip which is “Use join method for string concatenation for know list of items”. Consider the case we have n strings. We need to contact the strings. We can use the “+ operator” for concatenation or make a list and concatenate using the join method. Let's analyze this using an example.

code

import timeit

hello = "hello"
world = "world"
python = "Python"
is_ = "is"
easy = "easy"

def using_join():
    data = [hello, world, python, is_, easy]
    string = " ".join(data)
    return string

def using_concat():
    string = hello + " " + world + " " + python + " " + is_ + " " + easy
    return string

using_join_time = timeit.timeit(using_join, number=1000_000)
using_concat_time = timeit.timeit(using_concat, number=1000_000)

print(“Time taken by join: ”, using_join_time)
print(“Time taken by concat : ”, using_concat_time)

Output

Time taken by join: 0.12385872699815081

Time taken by concat:  0.24401297000076738

Why

If we analyze the code we can see that in joining there is only one operation is which is a function call. But in the other example, there are multiple binary additions happening this takes place this result in slowness

Tip

Use the join method instead of concatenation when we convert a list of item to a string.

Hope you have learned something from this post. Please share your suggestions with afsal@parseltongue.co.in