python字符串连接性能 [英] python string join performance

查看:75
本文介绍了python字符串连接性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网上有很多关于python性能的文章,你读的第一件事:连接字符串不应该使用'+'完成:避免使用s1+s2+s3,而是使用str.join

There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join

我尝试了以下方法:连接两个字符串作为目录路径的一部分:三种方法:

I tried the following: concatenating two strings as part of a directory path: three approaches:

  1. 我不应该做的'+'
  2. str.join
  3. os.path.join

这是我的代码:

import os,time

s1='/part/one/of/dir'
s2='part/two/of/dir'
N=10000

t=time.clock()
for i in xrange(N):
    s=s1+os.sep+s2
print time.clock()-t

t=time.clock()
for i in xrange(N):
    s=os.sep.join((s1,s2))
print time.clock()-t

t=time.clock()
for i in xrange(N):
    s=os.path.join(s1,s2)
print time.clock()-t

这里是结果(python 2.5 WinXP)

Here the results (python 2.5 WinXP)

0.0182201927899
0.0262544541275
0.120238186697

不应该正好相反吗?

推荐答案

确实不应该使用+".你的例子很特别,试试同样的代码:

It is true you should not use '+'. Your example is quite special, try the same code with:

s1='*'*100000
s2='+'*100000

然后第二个版本(str.join)要快得多.

Then the second version (str.join) is much faster.

这篇关于python字符串连接性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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