Is there an efficient mass string concatenation method in Python (like StringBuilder in C# or StringBuffer in Java)?
I found following methods here:
- Simple concatenation using
+
- Using a string list and the
join
method - Using
UserString
from theMutableString
module - Using a character array and the
array
module - Using
cStringIO
from theStringIO
module
What should be used and why?
ベストアンサー1
You may be interested in this: An optimization anecdote by Guido. Although it is worth remembering also that this is an old article and it predates the existence of things like ''.join
(although I guess string.joinfields
is more-or-less the same)
On the strength of that, the array
module may be fastest if you can shoehorn your problem into it. But ''.join
is probably fast enough and has the benefit of being idiomatic and thus easier for other Python programmers to understand.
Finally, the golden rule of optimization: don't optimize unless you know you need to, and measure rather than guessing.
You can measure different methods using the timeit
module. That can tell you which is fastest, instead of random strangers on the Internet making guesses.