为什么python元组工厂函数比列表工厂函数慢?

时间:2018-11-15 03:33:01

标签: python list performance tuples python-internals

尽管它们的表现几乎相同 但是我很好奇,因为根据are-tuples-more-efficient-than-lists-in-python,我认为元组比元组高效 有人知道吗?

>>> a = (i for i in range(100000))
>>> timeit.timeit('list(a)', 'from __main__ import a', number=1000)
0.011526490096002817
>>> a = (i for i in range(100000))
>>> timeit.timeit('tuple(a)', 'from __main__ import a', number=1000)
0.009374740999192



>>> a = [i for i in range(100000)]
>>> timeit.timeit('tuple(a)', 'from __main__ import a', number=1000)
0.35291082598268986
>>> timeit.timeit('list(a)', 'from __main__ import a', number=1000)
0.32638651994057


>>> a = {i for i in range(10000)}
>>> timeit.timeit('tuple(i for i in a)', 'from __main__ import a', number=1000)
0.4628257639706135
>>> timeit.timeit('[i for i in a]', 'from __main__ import a', number=1000)
0.20995741098886356
>>> timeit.timeit('list(map(lambda x: x, a))', 'from __main__ import a', number=1000)
0.9662498680409044

>>> timeit.timeit('x = (1,2,3,4,)', number=10000000)
0.13525238999864087
>>> timeit.timeit('x = [1,2,3,4,]', number=10000000)
0.5406758830067702

更新

>>> timeit.timeit('tuple([i for i in a])', 'from __main__ import a', number=10000)
27.79521625099005
>>> timeit.timeit('list([i for i in a])', 'from __main__ import a', number=10000)
27.748358012002427
>>> timeit.timeit('x = (1,2,3,4,)', number=10000000)
0.13525238999864087
>>> timeit.timeit('x = [1,2,3,4,]', number=10000000)
0.5406758830067702
>>> timeit.timeit('list([i for i in (1,2,3,4,5)])', 'from __main__ import a', number=1000000)
0.48201177397277206
>>> timeit.timeit('tuple([i for i in (1,2,3,4,5)])', 'from __main__ import a', number=1000000)
0.4545572029892355

我的中间结论:假设您正在构建json api服务,也许您应该:

  1. 使用列表理解而不是元组理解,因为使用元组理解时会调用函数
  2. 将生成器转换为数组时,请在元组()上使用list()
  3. 声明数组时,使用[x,x,]而不是[x,x,]

0 个答案:

没有答案