Now that I understand the difference between s.find()
and s.index()
in Python thanks to this question, I am wondering, which method is faster?
Is there any significant difference in term of speed other than potential overheads if we have to enclose s.index()
within a try/except
?
Is there any significant difference in term of speed other than potential overheads if we have to enclose
s.index()
within atry/except
.
In (C)Python at least, find
, index
, rfind
, rindex
are all wrappers around an internal function any_find_slice
.
The implementation is the same. The only difference is that index
and rindex
will raise a ValueError
for you if it finds that the result of calling any_find_slice
is -1
.
If you went ahead and timed these you'd see how there's clearly no meaningful difference between them:
➜ ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.find('b')"
Median +- std dev: 399 ns +- 7 ns
➜ ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.index('b')"
Median +- std dev: 396 ns +- 3 ns
I'm using perf
for the timings here.
I'm guessing in other implementations of Python this shouldn't differ. Both methods do the same thing and differ only in how they react when the requested element was not found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With