keinerweiss.de
2022/07/17

Python slow when concatenating strings

I was concatenating translation file contents to one string and observed rather long runtimes.

Turns out Python is not very efficient in this regard. So I reworked it to use a list.

strings_test.py
import time
 
start = time.time()
str1 = ""
for i in range(1,10000000):
    str1 += "A"*1000
print("Concat took: " + str(time.time() - start))
 
start = time.time()
str1 = ""
str2 = []
for i in range(1,10000000):
    str2.append("B"*1000)
print("List collection took: " + str(time.time() - start))
 
start = time.time()
str1 = "\n".join(str2)
print("Final join took: " + str(time.time() - start))
Concat took: 4.820241689682007
List collection took: 0.9731082916259766
Final join took: 2.7453043460845947