Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster between s.find() and s.index()

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?

like image 645
YeO Avatar asked Mar 02 '17 09:03

YeO


Video Answer


1 Answers

Is there any significant difference in term of speed other than potential overheads if we have to enclose s.index() within a try/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.

like image 175
Dimitris Fasarakis Hilliard Avatar answered Oct 14 '22 02:10

Dimitris Fasarakis Hilliard