Created
November 1, 2022 13:08
-
-
Save hofrob/95b0d31ee4e168b876ecf82c92db2df4 to your computer and use it in GitHub Desktop.
Compare timings of joining a list of strings vs adding strings onto strings
This file contains hidden or 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
import random | |
import string | |
import time | |
values = [] | |
for i in range(10): | |
values.append("".join(random.choices(string.ascii_letters + string.digits, k=10))) | |
n = 500000 | |
print(f"Construct {n=} strings with these random values: {values=}") | |
print("---") | |
begin_dict = time.time_ns() | |
for i in range(n): | |
string_to_add_to = "" | |
for value in values: | |
string_to_add_to += value | |
string_add_timing = time.time_ns() - begin_dict | |
begin_dict = time.time_ns() | |
for i in range(n): | |
list_to_join = [] | |
for value in values: | |
list_to_join.append(value) | |
"".join(list_to_join) | |
list_join_timing = time.time_ns() - begin_dict | |
print(f"{'string add:':>20} {string_add_timing / 10 ** 6:.1f}ms") | |
print(f"{'list join:':>20} {list_join_timing / 10 ** 6:.1f}ms") | |
percentage_difference = (string_add_timing - list_join_timing) / list_join_timing * 100 | |
print("---") | |
print(f"list join is {percentage_difference:.2f}% faster") |
Author
hofrob
commented
Nov 1, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment