In both statements, I am appending a character "a"
to the string s
:
s += "a"
s = s + "a"
Which statement has the better time complexity in Python?
In both statements, I am appending a character "a"
to the string s
:
s += "a"
s = s + "a"
Which statement has the better time complexity in Python?
They have the same time complexity.
In the general Python standard defined case: They both have the same time complexity of O(n), where n is the length of string s
.
In practice, with the CPython implementation: They can in some cases both be O(1), because of an optimization that the interpreter can do when it detects that s
is the only reference to the string in question.
Demo (using Python 3.10.1
):
O(1) (optimization in play):
String of length 10⁹, using +=
:
$ python -m timeit --setup='s = "s" * 10**9' 's += "a"'
5000000 loops, best of 5: 96.6 nsec per loop
String of length 10⁹, using +
:
$ python -m timeit --setup='s = "s" * 10**9' 's = s + "a"'
5000000 loops, best of 5: 95.5 nsec per loop
String of length 1, using +=
:
$ python -m timeit --setup='s = "s"' 's += "a"'
5000000 loops, best of 5: 97 nsec per loop
String of length 1, using +
:
$ python -m timeit --setup='s = "s"' 's = s + "a"'
5000000 loops, best of 5: 97.9 nsec per loop
O(n) (optimization doesn't apply):
String of length 10⁹, optimization doesn't apply, using +=
:
$ python -m timeit --setup='s = "s" * 10**9; b = s' 's += "a"'
1 loop, best of 5: 440 msec per loop
String of length 10⁹, optimization doesn't apply, using +
:
$ python -m timeit --setup='s = "s" * 10**9; b = s' 's = s + "a"'
1 loop, best of 5: 445 msec per loop
String of length 1, optimization doesn't apply, using +=
:
$ python -m timeit --setup='s = "s"; b = s' 's += "a"'
5000000 loops, best of 5: 85.8 nsec per loop
String of length 1, optimization doesn't apply, using +
:
$ python -m timeit --setup='s = "s"; b = s' 's = s + "a"'
5000000 loops, best of 5: 84.8 nsec per loop
More info about the time complexity of string concatenation: https://stackoverflow.com/a/37133870/9835872 https://stackoverflow.com/a/34008199/9835872
Strings in Python are immutable, so whenever you "append" to s, Python makes a copy of s and appends the new character, effectively taking O(n) time complexity for both.