python 3, 字符串连接速度

来源:互联网 发布:知乎付费问答 编辑:程序博客网 时间:2024/06/05 18:36

对比字符串连接速度,可以发现, 字符串少时, +快;
字符串多时, join快

from time import timedef method1():    t = time()    for i in range(100000):        s = 'hiweeds'+'hiweeds'+'hiweeds'+'hiweeds'+'hiweeds'+'hiweeds'+'hiweeds'+'hiweeds'+'hiweeds'+'hiweeds'    t1 = time()    print ("Time %f" % (t1 - t))def method2():    t = time()    for i in range(100000):        s = ''.join(['hiweeds','hiweeds','hiweeds','hiweeds','hiweeds','hiweeds','hiweeds','hiweeds','hiweeds','hiweeds'])    print (time() - t)print ('hello World')method1()method2()def method3():    t = time()    for i in range(100000):        s = 'hiweeds'+'hiweeds'+'hiweeds'+'hiweeds'    t1 = time()    print ("Time %f" % (t1 - t))def method4():    t = time()    for i in range(100000):        s = ''.join(['hiweeds','hiweeds','hiweeds','hiweeds'])    print (time() - t)print ('hello World')method3()method4()
0 0