Reputation: 5595
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
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
Reputation: 140276
it has to be faster.
n
you're looking in the variables (dictionaries) once.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