Skip to content

Latest commit

 

History

History
25 lines (18 loc) · 767 Bytes

20231218133029.md

File metadata and controls

25 lines (18 loc) · 767 Bytes

More performant string building

In Python, repeatedly concatenating strings using the + operator can be inefficient because strings are immutable, which means that each concatenation creates a new string and copies the old contents over.

A more efficient way is to build up a list of strings and then join them together in a single operation using the join() method:

import time

words = ["word"] * 100_000

# inefficient string concatenation
start_time = time.time()
sentence = ""
for w in words:
    sentence += w
print(time.time() - start_time)  # 0.9659469127655029

# more efficient string concat using .join() on list
start_time = time.time()
sentence = "".join(words)
print(time.time() - start_time)  # 0.001013040542602539

#strings #performance