Friday 13 September 2019

Python: Which is Quicker to Search a String, Find or In?

There are many ways to do the same task in Python, as with most things. Here I wanted to know which was quicker to see if a string contained a space:
if x.find(' ') != -1:
or
if ' ' in x:
So a little test...
import datetime x = 'abc def' r = 100000000 def test_a(): if x.find(' ') != -1: pass def test_b(): if ' ' in x: pass start = datetime.datetime.now() for a in range(0, r): test_a() print('Test A: ' + str(datetime.datetime.now()-start)) start = datetime.datetime.now() for a in range(0, r): test_b() print('Test B: ' + str(datetime.datetime.now()-start))
... found that ...
Test A: 0:00:27.240583 Test B: 0:00:13.469368
"in" being the clear winner here and no real surprise as "find" has to do more work to return the character's position.