Skip to content

Instantly share code, notes, and snippets.

@hofrob
Created November 1, 2022 13:08
Show Gist options
  • Save hofrob/95b0d31ee4e168b876ecf82c92db2df4 to your computer and use it in GitHub Desktop.
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
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")
@hofrob
Copy link
Author

hofrob commented Nov 1, 2022

Construct n=500000 strings with these random values: values=['fqyShRulwa', '5b9ZpxDlA0', 'dyjzPbZXHy', 'Chb1SDhiR5', 'Wu0ZzFPM4V', 'eRkIjWwFYC', 'EDfP0bVVrV', 'nxoMjNmwkI', 'Le5bDVdnoh', 'txYXjdnpF0']
---
         string add: 441.2ms
          list join: 355.2ms
---
list join is 24.21% faster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment