网络上有很多关于Python性能的文章。你第一眼看到的是不应该使用'+'来连接字符串;避免使用s1 + s2 + s3,而是使用str.join
我尝试了以下操作:将两个字符串作为目录路径的一部分进行连接,有三种方法:
- '+' 这是我不应该使用的方法
- str.join
- 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
以下是结果(在 Windows XP 上使用 Python 2.5):
0.0182201927899
0.0262544541275
0.120238186697
难道不该正好相反吗?