Search code examples
pythonvariable-length

Is it faster to use n = len(s) instead of using len(s) directly?


Often to save some time, I would like we to use n = len(s) in my local function. I am curious about which call is faster or they are the same?

while i < len(s):
  # do something

vs

while i < n:
  # do something

There should not be too much difference, but using len(s), we need to reach s first, then call s.length. This is O(1) + O(1). But using n, it is O(1). I assume so.


Solution

  • You're right, here's some benchmarks:

    s = np.random.rand(100)
    n = 100
    

    Above is setup.

    %%timeit
    50 < len(s)
    
    86.3 ns ± 2.4 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    

    Versus:

    %%timeit
    50 < n
    
    36.8 ns ± 1.15 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
    

    But then again, it's hard to imagine differences on ~60ns level would have affected speed. Unless you're calling len(s) millions of times.