Python 的字符串连接与 str.join 相比有多慢? [英] How slow is Python's string concatenation vs. str.join?

查看:30
本文介绍了Python 的字符串连接与 str.join 相比有多慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我对 this 的回答中的评论线程,我想知道 += 运算符和 ''.join()

As a result of the comments in my answer on this thread, I wanted to know what the speed difference is between the += operator and ''.join()

那么两者的速度对比如何?

So what is the speed comparison between the two?

推荐答案

来自:高效的字符串连接

方法一:

def method1():
  out_str = ''
  for num in xrange(loop_count):
    out_str += 'num'
  return out_str

方法四:

def method4():
  str_list = []
  for num in xrange(loop_count):
    str_list.append('num')
  return ''.join(str_list)

现在我意识到它们并不具有严格的代表性,第 4 种方法在迭代并加入每个项目之前附加到列表中,但这是一个公平的指示.

Now I realise they are not strictly representative, and the 4th method appends to a list before iterating through and joining each item, but it's a fair indication.

字符串连接明显快于串联.

String join is significantly faster then concatenation.

为什么?字符串是不可变的,不能就地更改.要改变一个,需要创建一个新的表示(两者的串联).

Why? Strings are immutable and can't be changed in place. To alter one, a new representation needs to be created (a concatenation of the two).

这篇关于Python 的字符串连接与 str.join 相比有多慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆