When did Python's += string concatenation suddenly become smart?

Правка en1, от Shisuko, 2021-08-30 04:23:40

For almost a decade now, I've been told to avoid using += on strings in Java and Python. Because they are immutable, the += creates an entirely new string and has to copy over all the characters from the left-hand side. Thus, putting a += in a loop could have your program's complexity degrade into quadratic in some cases if you're not careful.

But then just last week, I learned that CPython actually hands string concatenation smartly! On the Custom Test tab here on Codeforces, the following code runs in just 280ms when submitted to Python 3.8.10.

s = ''
for _ in range(10**6):
    s += 'a'
print(len(s))

(In contrast, it badly TLEs when submitting to PyPy 3.7, so I suppose that's one thing Python has over PyPy, but it's not like join was too hard to do, though, anyway).

Was this a recent change? How long have I been living a lie?

Теги #python 3, #string

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский Shisuko 2021-08-30 04:23:40 944 Initial revision (published)