Pythoner
Pythoner

Reputation: 5595

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.

Upvotes: 4

Views: 167

Answers (2)

Rocky Li
Rocky Li

Reputation: 5958

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.

Upvotes: 5

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140276

it has to be faster.

  • Using n you're looking in the variables (dictionaries) once.
  • Using len(s) you're looking twice (len is also a function that we have to look for). Then you call the function.

That said if you do while i < n: most of the time you can get away with a classical for i in range(len(s)): loop since upper boundary doesn't change, and is evaluated once only at start in range (which may lead you to: Why wouldn't I iterate directly on the elements or use enumerate ?)

while i < len(s) allows to compare your index against a varying list. That's the whole point. If you fix the bound, it becomes less attractive.

In a for loop, it's easy to skip increments with continue (as easy as it is to forget to increment i and end up with an infinite while loop)

Upvotes: 7

Related Questions