緣由是這樣的,字符串是不可變對象,當用操做符+鏈接字符串的時候,每執行一次+都會申請一塊新的內存,而後複製上一個+操做的結果和本次操做的右操做符到這塊內存空間,所以用+鏈接字符串的時候會涉及好幾回內存申請和複製。而join在鏈接字符串的時候,會先計算須要多大的內存存放結果,而後一次性申請所需內存並將字符串複製過去,這是爲何join的性能優於+的緣由。因此在鏈接字符串數組的時候,咱們應考慮優先使用join。
---------------------
做者:shs867
來源:CSDN
原文:https://blog.csdn.net/shs867/article/details/79924712
版權聲明:本文爲博主原創文章,轉載請附上博文連接!python
from time import time import functools BASE_STR = 'basebase' STRS = ['str_'+str(i) for i in range(10**6)] def excute_time(func): @functools.wraps(func) def inner(*args, **kw): start_time = time() res = func(*args, **kw) end_time = time() print('{} 執行耗時{:.3f}秒'.format(func.__name__, end_time-start_time)) return res return inner @excute_time def str_merge_by_add(): '''測試字符串相加''' result = '' for item in STRS: result += item @excute_time def str_merge_by_add2(): '''測試字符串相加''' result = '' for item in STRS: result = result + item @excute_time def str_merge_by_join(): '''測試join函數''' result = '' result = ''.join(STRS) if __name__ == '__main__': for i in range(3): str_merge_by_add() str_merge_by_add2() str_merge_by_join()
1. 由於省去了生成中間對象,join效率遠遠高於那種for循環中有臨時變量的代碼windows
2. =比+=用時要多數組
由於懷疑是for本身寫的臨時變量影響效率,遂寫成一連串字符串直接相加 app
from time import time import functools TOTAL = 10**6 # def excute_time(fun_name=None): # '''打印執行時間,若是傳入fun_name,則輸出語句顯示傳入名,不然顯示被裝飾函數的名字''' # def wrapper(func): # @functools.wraps(func) # def inner(*args, **kw): # print(args,kw) # start_time = time() # res = func(*args, **kw) # end_time = time() # print('{} 執行耗時{:.3f}秒'.format(fun_name or func.__name__, end_time-start_time)) # return res # return inner # return wrapper def excute_time(func): '''打印執行時間,顯示傳入的函數的名稱''' @functools.wraps(func) def inner(*args, **kw): start_time = time() res = func(*args, **kw) end_time = time() func_name = func.__name__ if type(args[0]) is type(excute_time): func_name = args[0].__name__ print('{} 執行耗時{:.3f}秒'.format(func_name, end_time-start_time)) return res return inner @excute_time def run(func, n=TOTAL): '''循環運行TOTAL次''' while n>0: func() n = n-1 def str_add(): '''字符串直接加''' result = 'ab' + 'ab' + 'ab' + 'ab' + 'ab' + 'ab' + 'ab' + 'ab' + 'ab' def str_add2(): '''字符串直接加''' temp = ['ab', 'ab', 'ab', 'ab', 'ab', 'ab', 'ab', 'ab', 'ab'] result = 'ab' + 'ab' + 'ab' + 'ab' + 'ab' + 'ab' + 'ab' + 'ab' + 'ab' def str_join(): temp = ['ab', 'ab', 'ab', 'ab', 'ab', 'ab', 'ab', 'ab', 'ab'] result = ''.join(temp) if __name__ == '__main__': for i in range(3): run(str_add) run(str_add2) run(str_join)
可發現join比字符串直接相加要慢,彷佛網上常見的說法有問題,我的猜想,錯誤之處請指出ide