len(List) 与读取变量的性能 [英] perfomance of len(List) vs reading a variable
问题描述
一个类似的问题已经在 len() 函数的成本这里问过.但是,这个问题着眼于 len
本身的成本.假设,我有一段代码重复多次len(List)
,每次都是O(1)
,读取一个变量也是O(1)
加上赋值也是 O(1)
.
A similar question has already been ask Cost of len() function here. However, this question looks at the cost of len
it self.
Suppose, I have a code that repeats many times len(List)
, every time is O(1)
, reading a variable is also O(1)
plus assigning it is also O(1)
.
作为旁注,我发现 n_files = len(Files)
比我的代码中重复的 len(Files)
更具可读性.所以,这已经是我做这件事的动力.你也可以反对我,代码中的某处 Files
可以被修改,所以 n_files
不再正确,但事实并非如此.
As a side note, I find that n_files = len(Files)
is somewhat more readable than repeated len(Files)
in my code. So, that is already an incentive for me to do this.
You could also argue against me, that somewhere in the code Files
can be modified, so n_files
is no longer correct, but that is not the case.
我的问题是:
是调用 len(Files)
之后访问 n_files
的次数会更快吗?
My question is:
Is the a number of calls to len(Files)
after which accessing n_files
will be faster?
推荐答案
一些结果(时间,以秒为单位,一百万次调用),在 Windows 7 上使用 Python 2.7.10 的十元素列表;store
是我们存储长度还是一直调用len
,alias
是我们是否为len<创建本地别名/代码>:
A few results (time, in seconds, for one million calls), with a ten-element list using Python 2.7.10 on Windows 7; store
is whether we store the length or keeping calling len
, and alias
is whether or not we create a local alias for len
:
Store Alias n= 1 10 100
Yes Yes 0.862 1.379 6.669
Yes No 0.792 1.337 6.543
No Yes 0.914 1.924 11.616
No No 0.879 1.987 12.617
和一千个元素的列表:
Store Alias n= 1 10 100
Yes Yes 0.877 1.369 6.661
Yes No 0.785 1.299 6.808
No Yes 0.926 1.886 11.720
No No 0.891 1.948 12.843
结论:
- 存储结果比重复调用
len
更有效率,即使对于n == 1
; - 为
len
创建一个本地别名可以对较大的n
进行小的改进,我们不存储结果,但不如只存储结果;和 - 列表长度的影响可以忽略不计,这表明整数是否被 intern 没有任何区别.
- Storing the result is more efficient than calling
len
repeatedly, even forn == 1
; - Creating a local alias for
len
can make a small improvement for largern
where we aren't storing the result, but not as much as just storing the result would; and - The influence of the length of the list is negligible, suggesting that whether or not the integers are interned isn't making any difference.
测试脚本:
def test(n, l, store, alias):
if alias:
len_ = len
len_l = len_(l)
else:
len_l = len(l)
for _ in range(n):
if store:
_ = len_l
elif alias:
_ = len_(l)
else:
_ = len(l)
if __name__ == '__main__':
from itertools import product
from timeit import timeit
setup = 'from __main__ import test, l'
for n, l, store, alias in product(
(1, 10, 100),
([None]*10,),
(True, False),
(True, False),
):
test_case = 'test({!r}, l, {!r}, {!r})'.format(n, store, alias)
print test_case, len(l),
print timeit(test_case, setup=setup)
这篇关于len(List) 与读取变量的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!