Created
September 1, 2021 03:42
-
-
Save geniusnhu/15df496039347099ba0a8c893c788f87 to your computer and use it in GitHub Desktop.
Concatenate strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 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