python字符串拼接效率比较

直接看代码

方式一:

import time
start_time = time.perf_counter()
s = ''
for n in range(0,1000):
    s += str(n)
end_time = time.perf_counter()

print('Time elapse:{}'.format(end_time - start_time))

方式二:

import time
start_time = time.perf_counter()
s = []
for n in range(0,1000):
    s.append(str(n))
''.join(s)
end_time = time.perf_counter()
print('Time elapse:{}'.format(end_time - start_time))

方式三:

import time
start_time = time.perf_counter()
s = ''.join(map(str,range(0,1000)))
end_time = time.perf_counter()
print('Time elapse:{}'.format(end_time - start_time))

条数和时间效果如下:

方案\条数 1000 100000(十万条) 10000000(一千万条)
方式一(+=)
0.0006100520004110876
0.053987349001545226
5.24716751743108
方式二(list,join)
0.00047015399832162075
0.038282303998130374
4.119422915999166
方式三(map,join)
0.00022071799685363658
0.021825258001626935
2.6899159259992302

根据时间总结出,1000条时方式一优于方式二,十万条及以后,就是方式二优于方式一了,但方式三一直都是最优方式。

 

你可能感兴趣的:(python)