4 ms·
The advice from Python core developers is not to rely on that optimization — it is fragile and implementation dependent. Instead, please use str.join() to conc
by raymondh 6y ago
The advice from Python core developers is not to rely on that optimization — it is fragile and implementation dependent. Instead, please use str.join() to concatenate a bunch of strings together. That is guaranteed to not be quadratic.
When Armin Rigo's brilliant optimization was added, the rationale was mitigation-of-harm: it could sometimes save users who weren't following the advice. Also it sometimes helped with the then common technique of building a short string with series of concatenations done with "+":
advice = 'Dear ' + customer + ', please buy ' + product + '.'
Nowadays, that would be done efficiently with an f-string:
advice = f'Dear {customer}, please buy {product}.'
One other personal thought as a code reviewer and teacher: If you teach someone to build strings with "+" or "+=" and the optimization prevents a negative consequence, then don't be surprised if they try this with other sequence types where no such optimization exists.
Really, just learn str.join() and itertools.chain(). Both of those scale nicely.
- nayuki 6y agoInterestingly in Java, at the language level, string concatenation is translated like this: x + "s" + y + "t" + z --> new java.lang.StringBuilder().append(x).append("s").append(y).append("t").append(z).toString() and not naively like this: java.lang.String.valueOf(x).concat("s").concat(String.valueOf(y)).concat("t").concat(String.valueOf(z)) > just learn str.join() Or Python io.StringIO .