Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex vs. Manual comparison. Which is faster?

in writing a scripting engine, I have functions like (psuedo-code)

function is_whitespace?(char c){
  return c==' ' || c=='\t' || c=='\r' || c=='\n';
}

Well, my question is which is faster in most langugaes? That or using regex like

function is_whitespace?(char c){
  return regex_match('\s',c);
}

The chief languages I'm concerned with are C#, C, and Ruby also in case it is completely platform-dependent.

like image 662
Earlz Avatar asked Apr 05 '10 18:04

Earlz


2 Answers

Of course four comparisons of small chunks of memory are greatly faster (and using almost no memory) than building, running and destroying a state machine.

like image 154
wRAR Avatar answered Nov 08 '22 04:11

wRAR


The manual comparison is faster to execute, the regex comparison is faster to type.

Note that your two implementations are not equivalent if your system uses Unicode. The regex \s matches all Unicode whitespace while your manual comparison only handles basic ASCII and does not even include the vertical tab and form feed characters which are usually also considered whitespace.

If you're writing this in a high-level language I'd suggest using the is_whitespace() function already provided by your programming language's libraries. A basic function like that is almost always included.

So in the end the answer is "it depends". In some situations the extra programming effort of using procedural code is warranted. In many cases the regex is fast enough and easier to maintain.

like image 28
Jan Goyvaerts Avatar answered Nov 08 '22 04:11

Jan Goyvaerts