Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster, Regex or if compares - Java

I have two possibilities, make a regex or make a if compare.

If Compares

if (!(modoImpressao.equals("IMPRESSORA") || 
   modoImpressao.equals("PDF") || modoImpressao.equals("AMBOS")))

Regex Match

if (!Pattern.compile("(IMPRESSORA)|(PDF)|(AMBOS)",Pattern.DOTALL).matcher(modoImpressao).find()){
            throw new EspdNeverStopParametroInvalidoException(TspdConstMessages.IMPRIMIR_PARAMETRO_MODOIMPRESSAO_INVALIDO,"TspdImprimirNFCe");
        }

which one is faster?

like image 404
Leonardo Galdioli Avatar asked Jan 10 '14 19:01

Leonardo Galdioli


1 Answers

The first snippet will almost certainly be faster, since it doesn't have to parse a regular expression and perform a match against it. Another alternative is:

if (Arrays.asList("IMPRESSORA", "PDF", "AMBOS").contains(modoImpressao)

which shouldn't differ speed-wise much from your first snippet, but is arguably more readable and concise.

Regular expressions are great, but only use them when you need to. This situation definitely doesn't warrant the use of regexes; all you're doing is comparing against literal strings.

There's an old saying by Jamie Zawinski that goes like this:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

like image 103
arshajii Avatar answered Sep 30 '22 16:09

arshajii