perfomance of len(List) vs reading a variable

前端 未结 4 553
名媛妹妹
名媛妹妹 2021-01-12 17:17

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 repea

4条回答
  •  -上瘾入骨i
    2021-01-12 17:39

    Function calls in python are costly, so if you are 100% sure that the size of n_files would not change when you are accessing its length from the variable, you can use the variable, if that is what is more readable for you as well.

    An Example performance test for both accessing len(list) and accessing from variable , gives the following result -

    In [36]: l = list(range(100000))
    
    In [37]: n_l = len(l)
    
    In [40]: %timeit newn = len(l)
    10000000 loops, best of 3: 92.8 ns per loop
    
    In [41]: %timeit new_n = n_l
    10000000 loops, best of 3: 33.1 ns per loop
    

    Accessing the variable is always faster than using len() .

提交回复
热议问题