python中最有效的字符串连接方法是什么? [英] What is the most efficient string concatenation method in python?
问题描述
Python 中是否有任何有效的大量字符串连接方法(例如 C# 中的 StringBuilder 或 Java 中的 StringBuffer)?我在这里找到了以下方法:
Is there any efficient mass string concatenation method in Python (like StringBuilder in C# or StringBuffer in Java)? I found following methods here:
- 使用
+
的简单连接 - 使用字符串列表和
join
方法 - 使用
MutableString
模块中的UserString
- 使用字符数组和
array
模块 - 使用
StringIO
模块中的cStringIO
- Simple concatenation using
+
- Using string list and
join
method - Using
UserString
fromMutableString
module - Using character array and the
array
module - Using
cStringIO
fromStringIO
module
但是你们专家使用或建议什么,为什么?
But what do you experts use or suggest, and why?
推荐答案
您可能对此感兴趣:Guido 的优化轶事.虽然值得记住的是,这是一篇旧文章,它早于诸如 ''.join
之类的东西的存在(尽管我猜 string.joinfields
是更多或 -不一样)
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)
就这一点而言,array
模块可能是最快的,如果你能把你的问题硬塞进去.但是 ''.join
可能足够快并且具有惯用的好处,因此其他 Python 程序员更容易理解.
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.
您可以使用 timeit
模块测量不同的方法.这可以告诉你哪个最快,而不是互联网上的随机陌生人猜测.
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.
这篇关于python中最有效的字符串连接方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!