pythontime-complexity

Is the time complexity of string += "a" the same as string = string + "a"?


In both statements, I am appending a character "a" to the string s:

  1. s += "a"
  2. s = s + "a"

Which statement has the better time complexity in Python?


Solution

  • 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.13.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: 48.4 nsec per loop
    

    String of length 10⁹, using +:

    $ python -m timeit --setup='s = "s" * 10**9' 's = s + "a"'
    5000000 loops, best of 5: 48.9 nsec per loop
    

    String of length 1, using +=:

    $ python -m timeit --setup='s = "s"' 's += "a"'
    5000000 loops, best of 5: 45.2 nsec per loop
    

    String of length 1, using +:

    $ python -m timeit --setup='s = "s"' 's = s + "a"'
    5000000 loops, best of 5: 45.3 nsec per loop
    

    O(n) (optimization doesn't apply, as the lambda f references s):

    String of length 10⁹, optimization doesn't apply, using +=:

    $ python -m timeit --setup='s = "s" * 10**9; f = lambda: s' 's += "a"'
    2 loops, best of 5: 122 msec per loop
    

    String of length 10⁹, optimization doesn't apply, using +:

    $ python -m timeit --setup='s = "s" * 10**9; f = lambda: s' 's = s + "a"'
    2 loops, best of 5: 115 msec per loop
    

    String of length 1, optimization doesn't apply, using +=:

    $ python -m timeit --setup='s = "s"; f = lambda: s' 's += "a"'
    100000 loops, best of 5: 2.32 usec per loop
    

    String of length 1, optimization doesn't apply, using +:

    $ python -m timeit --setup='s = "s"; f = lambda: s' 's = s + "a"'
    100000 loops, best of 5: 2.45 usec per loop
    

    More info about the time complexity of string concatenation: https://stackoverflow.com/a/37133870/9835872 https://stackoverflow.com/a/34008199/9835872