Skip to content

Instantly share code, notes, and snippets.

@denis-ryzhkov
Created June 8, 2020 11:17
Show Gist options
  • Save denis-ryzhkov/386cc5b2a9da3e26eaec2fb9a711f017 to your computer and use it in GitHub Desktop.
Save denis-ryzhkov/386cc5b2a9da3e26eaec2fb9a711f017 to your computer and use it in GitHub Desktop.
Python str concat benchmark
#!/usr/bin/env python
"""
Python str concat benchmark
Copyright (C) 2013-2020 by Denis Ryzhkov <[email protected]>
MIT License, see http://opensource.org/licenses/MIT
"""
from time import time
import sys
is_py3 = sys.version_info.major == 3
if is_py3:
xrange = range
a = "hello"
b = "world"
loops = 10 ** 6
results = []
start = time()
for _ in xrange(loops):
result = ",".join((a, b))
results.append(("join", time() - start))
start = time()
for _ in xrange(loops):
result = a + "," + b
results.append(("+", time() - start))
start = time()
for _ in xrange(loops):
result = "%s,%s" % (a, b)
results.append(("%", time() - start))
start = time()
for _ in xrange(loops):
result = "{},{}".format(a, b)
results.append(("format", time() - start))
if is_py3: # Else comment-out: f-strings are not supported in py2
start = time()
for _ in xrange(loops):
result = f"{a},{b}"
results.append(("f-string", time() - start))
for name, value in sorted(results, key=lambda row: row[1]):
print("{:>10} {:7.6}".format(name, value))
"""
Results:
# 2013-02-27, python-2.?
+ 0.977680
join 1.388858
% 1.507211
format 1.986074
# 2020-06-08, python-2.7.17
+ 0.097954
join 0.152078
% 0.165025
format 0.210494
# 2020-06-08, python-3.8.2
f-string 0.158507
+ 0.192736
join 0.208459
% 0.273779
format 0.367376
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment