Skip to content

Instantly share code, notes, and snippets.

@geniusnhu
Created September 1, 2021 03:42
Show Gist options
  • Save geniusnhu/15df496039347099ba0a8c893c788f87 to your computer and use it in GitHub Desktop.
Save geniusnhu/15df496039347099ba0a8c893c788f87 to your computer and use it in GitHub Desktop.
Concatenate strings
### Concatenate string using '+' operation
def add_string_with_plus(iters):
s = ""
for i in range(iters):
s += "abc"
assert len(s) == 3*iters
### Concatenate strings using join() function
def add_string_with_join(iters):
l = []
for i in range(iters):
l.append("abc")
s = "".join(l)
assert len(s) == 3*iters
### Compare speed
>>> timeit(add_string_with_plus(10000))
100 loops, best of 5: 3.74 ms per loop
>>> timeit(add_string_with_join(10000))
100 loops, best of 5: 2.3 ms per loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment