Last active
July 28, 2022 02:33
-
-
Save kevinburke/6144826 to your computer and use it in GitHub Desktop.
Performance of ''.join vs .format() in Python
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
$ python test_time.py | |
join_test: 21.3 seconds | |
format_test: 36.6 seconds | |
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
j_setup = """ | |
def join_test(s1, s2, s3): | |
return ''.join([s1, "foo", s2, "foo", s3]) | |
a = 'foo' * 1000 | |
b = 'baz' * 1000 | |
c = 'bang' * 1000 | |
""" | |
j = """ | |
join_test(a, b, c) | |
""" | |
f_setup = """ | |
def format_test(s1, s2, s3): | |
return '{}foo{}foo{}'.format(s1, s2, s3) | |
a = 'foo' * 1000 | |
b = 'baz' * 1000 | |
c = 'bang' * 1000 | |
""" | |
f = """ | |
format_test(a, b, c) | |
""" | |
import timeit | |
jointimer = timeit.Timer(j, j_setup) | |
print jointimer.timeit(number=20000000) | |
formattimer = timeit.Timer(f, f_setup) | |
print formattimer.timeit(number=20000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
They seem to hold. With python 2.7.15, the differences are even more pronounced than your published results:
Python 3.7.7 (altered the
print
statements and nothing else):This benchmark indicates improved performance using tuples instead of list constructions on 2.7.15, but no significant difference in performance between the first two tests on Python 3.7.7:
2.7.15:
3.7.7:
The non-mutated-list-literal optimizations in Python 3 can be "defeated" by using
''.join([s1, "foo"] + [s2, "foo", s3])
and''.join((s1, "foo") + (s2, "foo", s3))
for their respective test functions, at which point the tuple version gains an advantage on both 2 and 3, though the advantage is significantly more pronounced on 2.7.15:2.7.15:
3.7.7:
All tests were run on an idle/stock MacBook Pro 2019 i9 2.3GhZ, with an updated OSX 10.14.6 and latest XCode/SDK/headers as of April 12, 2020, using
pyenv
-installed Pythons 2.7.15 and 3.7.7 (compiled and installed on April 12, 2020) with no compiler flag or library customizations.