爱上python系列------python性能(五):字符串拼接性能优化

python里面字符串是不可变的,在拼接的时候 速度会比较慢,因为拼接任意不可变序列都会生成一个新的序列对象

也就是说在拼接的过程中会产生很多中间对象,新建对象肯定需要时间,而且这明显浪费内存

优化的方式是使用.join()代替

实验代码如下:

import time
import numpy as np

ls=['AA_'+str(i) for i in range(10000000)]
s=""
st=time.time()
for i in ls:
    s+=i

print(time.time()-st)
#print(s)
s=""
st=time.time()
s=s.join(ls)
#print(s)
print(time.time()-st)

运行结果:

0.9245333671569824
0.08815383911132812

从结果可以看出,直接进行拼接的速度直接会慢是十倍以上,因此平时在进行字符串进行拼接的时候需要注意。

猜你喜欢

转载自blog.csdn.net/zhou_438/article/details/109245351