0

Which of these two operations should be faster? All I want to do is to check if one string is in another. We will ignore case, string-parts, whitespaces and all the like.

I'm assuming the first one, since it checks for existence only, if I'm right, while the latter checks also for position. Are these two operations the best standard ways to search for string anyway?

string = "my foo is your bar"

if "foo" in string:
 # do important things

if string.find("foo") > -1:
 #do much more important stuff
Dr.Elch
  • 2,105
  • 2
  • 17
  • 23
  • 2
    As pointed out in the linked duplicate, `in` is faster; it doesn't need to return a position or `-1` like `.find()` does, and doesn't require an attribute lookup and function call (which requires a frame stack push and pop). – Martijn Pieters Mar 05 '14 at 12:14
  • Hmm I wonder why I couldn't find that other question... – Dr.Elch Mar 05 '14 at 12:34

1 Answers1

1

You can try a python test, look:

from timeit import timeit
import re

def find(string, text):
    if string.find(text) > -1:
       pass


def best_find(string, text):
    if text in string:
       pass

print timeit("find(string, text)", "from __main__ import find; string='lookforme'; text='look'")  

print timeit("best_find(string, text)", "from __main__ import best_find; string='lookforme'; text='look'") 

The result:

0.441393852234
0.251421928406

Answer taken from here. As you see "in" is abetter option, in case you want to optimize your code.

Community
  • 1
  • 1
ederollora
  • 1,165
  • 2
  • 11
  • 29