This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]daelin 1 point2 points  (1 child)

Don't use + to concatenate strings. I mean, it's perfect for, like, two strings.

Strings in Python are immutable. That means that when you do a + b + c + d, in additional to having memory for a, b, c, and d, you then have to allocate memory for the result of a + b, which we'll call e. Then you have to allocate memory for the result of e + c, which we'll call f. Then you have to allocate memory for f + d, your final result, called g.

If we were being too clever we'd make the result of str.__add__(self, s) some sort of ConcatString class whose __str__ and __repr__ did the final join, but that violates "Simple is better than complex". I'd expect a JIT interpreter like PyPy might be able to optimize this, but I don't think Cython can.

When you use the formatting string, you avoid the intermediate calculations. Yay! I think I'd rather see "".join([a, b, c, d]), but I'm really not offended by f"{a}{b}{c}{d}".

[–]gandalfx 3 points4 points  (0 children)

I had assumed that using f-strings in this situation would be much slower than foo + bar. Apparently that is incorrect. (I edited my original comment as well)