Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How good is startswith?

Tags:

Is

text.startswith('a')  

better than

text[0]=='a'  

?

Knowing text is not empty and we are only interested in the first character of it.

like image 258
dugres Avatar asked Aug 22 '09 09:08

dugres


2 Answers

text[0] fails if text is an empty string:

IronPython 2.6 Alpha (2.6.0.1) on .NET 4.0.20506.1
Type "help", "copyright", "credits" or "license" for more information.
>>> text = ""
>>> print(text.startswith("a"))
False
>>> print(text[0]=='a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index out of range: 0

EDIT: You say you "know" that text is not empty... how confident are you of that, and what would you want to happen if it is empty in reality? If a failure is appropriate (e.g. it means a bug in your code) that would encourage the use of text[0]=='a'.

Other questions:

  • How concerned are you about the performance of this? If this is performance critical, then benchmark it on your particular Python runtime. I wouldn't be entirely surprised to find that (say) one form was faster on IronPython and a different one faster on CPython.

  • Which do you (and your team) find more readable?

like image 166
Jon Skeet Avatar answered Nov 15 '22 13:11

Jon Skeet


I'd agree with the others that startswith is more readable, and you should use that. That said, if performance is a big issue for such a special case, benchmark it:

$ python -m timeit -s 'text="foo"' 'text.startswith("a")'
1000000 loops, best of 3: 0.537 usec per loop

$ python -m timeit -s 'text="foo"' 'text[0]=="a"'
1000000 loops, best of 3: 0.22 usec per loop

So text[0] is amost 2.5 times as fast - but it's a pretty quick operation; you'd save ~0.3 microseconds per compare depending on the system. Unless you're doing millions of comparisons in a time critical situation though, I'd still go with the more readable startswith.

like image 42
Brian Avatar answered Nov 15 '22 13:11

Brian