使用元组或列表,string.join会更快吗?

Ras*_*taf 2 python string join tuples list

如果我可以选择

''.join( ['a', 'b'] )
Run Code Online (Sandbox Code Playgroud)

''.join( ('a', 'b') )
Run Code Online (Sandbox Code Playgroud)

我应该使用哪一个(哪一个更快)?有关系吗?

Ash*_*ary 5

它们几乎相同,您可以随时使用timeit模块计算代码:

In [145]: small_lis,small_tup = ['a','b']*10, ('a','b')*10

In [146]: avg_lis,avg_tup = ['a','b']*1000, ('a','b')*1000

In [147]: huge_lis,huge_tup = ['a','b']*10**6, ('a','b')*10**6
Run Code Online (Sandbox Code Playgroud)

当项目数为20时,计时结果:

>>> %timeit ''.join(small_lis)
1000000 loops, best of 3: 987 ns per loop

>>> %timeit ''.join(small_tup)
1000000 loops, best of 3: 1 us per loop
Run Code Online (Sandbox Code Playgroud)

平均尺寸(2000件):

>>> %timeit ''.join(avg_lis)
10000 loops, best of 3: 71.5 us per loop

>>> %timeit ''.join(avg_tup)
10000 loops, best of 3: 72.8 us per loop
Run Code Online (Sandbox Code Playgroud)

大尺寸(2*10**6件):

>>> %timeit ''.join(huge_lis)
1 loops, best of 3: 79.9 ms per loop

>>> %timeit ''.join(huge_tup)
1 loops, best of 3: 77.5 ms per loop
Run Code Online (Sandbox Code Playgroud)