Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 712
Pythoner Avatar asked Dec 13 '22 13:12

Pythoner


1 Answers

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)

like image 180
Jean-François Fabre Avatar answered Dec 22 '22 16:12

Jean-François Fabre