关于python字符串处理简单优化
import time
def main1():
st=time.clock()
s=""
for x in range(20000):
s="%s%s"%(s,x)
teststr=s
print "main1 len=%s time:%s"%(len(teststr),time.clock()-st)
def main2():
st=time.clock()
s=[]
for x in range(20000):
s.append("%s"%x)
teststr=" ".join(s)
print "main2 len=%s time:%s"%(len(teststr),time.clock()-st)
main1()
main2()
def main1():
st=time.clock()
s=""
for x in range(20000):
s="%s%s"%(s,x)
teststr=s
print "main1 len=%s time:%s"%(len(teststr),time.clock()-st)
def main2():
st=time.clock()
s=[]
for x in range(20000):
s.append("%s"%x)
teststr=" ".join(s)
print "main2 len=%s time:%s"%(len(teststr),time.clock()-st)
main1()
main2()
输出结果如下:
main1 len=88890 time:0.9
main2 len=88890 time:9.55
这就是通过%s%s和list来处理字符串的性能比较
转载于:https://blog.51cto.com/flandycheng/389619