7

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?

Community
  • 1
  • 1
YeO
  • 938
  • 1
  • 9
  • 17

1 Answers1

10

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Thanks, so they are indeed the very same function internally. So I guess there should not be any noticeable speed/performance difference then... – YeO Mar 02 '17 at 09:46
  • @YeO you generally need to guard against exceptions thrown with `str.index` but that's the only thing that would make it slower. Besides that, they do the same thing. – Dimitris Fasarakis Hilliard Mar 02 '17 at 09:49
  • Just wanted to add that in both these profiles, the substring is found, so there is no substantial difference. When the substring is NOT found, then you have a big difference between the two (index being a lot slower). – augustomen Aug 04 '20 at 18:40