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

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

问题描述

由于我在此答案中的评论线程,我想知道+=运算符和''.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?

推荐答案

来自:有效的字符串连接

方法1:

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

方法4:

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天全站免登陆