5 ms·
Most of the advice here seems okay but this stuck out to me: foo += 'ooo' # This is bad, instead you should do: foo = ''.join([foo, 'ooo']) This seem
by raziel2p 7y ago
Most of the advice here seems okay but this stuck out to me:
foo += 'ooo' # This is bad, instead you should do:
foo = ''.join([foo, 'ooo'])
This seems like such a silly micro-optimization. I also have to question its validity, even in scenarios where you're working with huge strings.
- lifeisstillgood 7y agoI would agree with you. The only reason I can see for the advice is that the first line does not handle that foo (#) might be other than a string - for example if foo was [1,2,3] you just got [1,2,3,'ooo']. the second line would barf on that. But if that was the case it is waaaay more readable to explicitly test for that so yeah, generally not great advice (#) Holy moly how many times will autocorrect change foo to too!!! stop it!
- deleted 7y ago[deleted]
- dragonwriter 7y agoIt's not so much large strings as lots of concatenation; aggregating all the substrings into a list and joining saves allocations and at least at one point in time it gave a huge speedup on a number of large systems. While Python's overall performance has improved since then, my understanding is that creating lots of strings and incrementally assembling the allocating and dropping lots of progressively-larger items is still often a significant performance hit.
- Hamuko 7y agoAs far as I am aware, str.join instead of str += is just a legacy optimisation that is not really valid when developing for modern Python versions.
- teddyh 7y agoIf you use += in a loop over a sequence, then you should replace it with a single line of join(), which should be more efficient. Otherwise you’re absolutely right.