Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance overhead/improvement using regular expressions

If I need to check if for example a word A or word B exists in a text (String), is there a performance difference if I do:

if(text.contains(wordA) || text.contains(wordB))

to using some regular expression that searches the string?
Does it depend on the regular expression format?
Or is it just a matter of taste?

UPDATE:
If text.contains(wordA) is false then the text.contains(wordB) will be evaluated.
This means that contains will be called twice.

I was thinking if in performance terms a regex might be better than calling contains twice.

like image 789
Cratylus Avatar asked Dec 06 '22 17:12

Cratylus


2 Answers

The code you have expresses your intent clearly, is more readable than a regexp, and is also probably faster.

Anyway, there is a very low probability that this part of your code causes any significant performance problem. So I wouldn't worry about performance here, but about readability and maintainability.

like image 175
JB Nizet Avatar answered Dec 09 '22 07:12

JB Nizet


While the performance of regular expression is lower, it has more expressive power and often this is more important. For example.

 "performance".contains("form") // is true

this may not be wheat you intended by a "word" Instead you can have a pattern

 "\\bform\\b"

This will only match a complete word in a string which can be at the start or the end.

like image 32
Peter Lawrey Avatar answered Dec 09 '22 06:12

Peter Lawrey