在以下拆分案例中,什么更快,更有效?

时间:2014-08-20 07:11:32

标签: python performance split code-efficiency

什么是更快,更有效,多次拆分并将结果存储在变量中:

text = 'Allah is all in all. Allah sees you, and is with you, wherever you are, whatever you do.'

wahed_al_surat = text.split(',')[0]
thalatha_al_surat = text.split(',')[1]
tnan_al_surat = text.split(',')[2]
arbaa_al_surat = text.split(',')[3]

或存储拆分列表一次,然后按索引访问并将它们存储在变量中:

text = 'Allah is all in all. Allah sees you, and is with you, wherever you are, whatever you do.'

splitted = text.split(',') # List accessible by split
wahed_al_surat = splitted[0]
thalatha_al_surat = splitted[1]
tnan_al_surat = splitted[2]
arbaa_al_surat = splitted[3]

如果不是更快,那么两种方式之间的CPU和内存效率会更高吗?

2 个答案:

答案 0 :(得分:3)

调用.split()只需一次就会更快,而您只需创建一次列表对象即可启动。 Python不会优化或内联额外的方法调用,因为它无法确定每次都会产生相同的结果。

你在这里有第三种选择:

wahed_al_surat, thalatha_al_surat, tnan_al_surat, arbaa_al_surat = text.split(',')

这只拆分一次,并将4个结果部分中的每一个分配给4个名称。

答案 1 :(得分:1)

对于此类问题,您可以随时查看使用timeit模块所花费的时间,如下所示

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import timeit
>>> 
>>> 
>>> code_to_test_1 = """
... text = 'Allah is all in all. Allah sees you, and is with you, wherever you are, whatever you do.'
... 
... wahed_al_surat = text.split(',')[0]
... thalatha_al_surat = text.split(',')[1]
... tnan_al_surat = text.split(',')[2]
... arbaa_al_surat = text.split(',')[3]
... """
>>> 
>>> 
>>> code_to_test_2 = """
... text = 'Allah is all in all. Allah sees you, and is with you, wherever you are, whatever you do.'
... 
... splitted = text.split(',') # List accessible by split
... wahed_al_surat = splitted[0]
... thalatha_al_surat = splitted[1]
... tnan_al_surat = splitted[2]
... arbaa_al_surat = splitted[3]
... """
>>> 
>>> 
>>> timeit.timeit(code_to_test_1, number=10000000)
14.445806980133057
>>> 
>>> 
>>> timeit.timeit(code_to_test_2, number=10000000)
4.4506120681762695
>>>