18

I'm writing PHP code to parse a string. It needs to be as fast as possible, so are regular expressions the way to go? I have a hunch that PHP string functions are more expensive, but it's just a guess. What's the truth?

Here's specifically what I need to do with the string:

Grab the first half (based on the third location of a substring "000000") and compare its hash to the next 20 bytes, throwing away anything left.

Parse the 9th byte through the next "000000" as one piece of data. Then grab the next 19 bytes after that, and split that into 8 (toss 1) and 8. Then I do some other stuff that converts those two 8 byte strings into dates.

So that's the kind of thing I need to do.

9 Answers 9

16

It depends on your case: if you're trying to do something fairly basic (eg: search for a string, replace a substring with something else), then the regular string functions are the way to go. If you want to do something more complicated (eg: search for IP addresses), then the Regex functions are definitely a better choice.

I haven't profiled regexes so I can't say that they'll be faster at runtime, but I can tell you that the extra time spent hacking together the equivalent using the basic functions wouldn't be worth it.


Edit with the new information in the OP:

It sounds as though you actually need to do a number of small string operations here. Since each one individually is quite basic, and I doubt you'd be able to do all those steps (or even a couple of those steps) at one time using a regex, I'd go with the basic functions:

Grab the first half (based on the third location of a substring "000000") and compare its hash to the next 20 bytes, throwing away anything left.

Use: strpos() and substr()
Or : /$(.*?0{6}.*?0{6}.*?)0{6}/

Then grab the next 19 bytes after that, and split that into 8 (toss 1) and 8.

Use: substr() - (I assume you mean 17 bytes here -- 8 + 1 + 8)

$part1 = substr($myStr, $currPos, 8);
$part2 = substr($myStr, $currPos + 9, 8);
2
  • 1
    Regexp are surprisingly efficient. You shouldn't generally be afraid of using them as the default tool.
    – troelskn
    Mar 11, 2009 at 21:10
  • 1
    @troelskn however, php's documentation mention that they are generally slower than basic php function for most basic operation since those do not use the regex engine.
    – T0xicCode
    Feb 20, 2012 at 12:36
6

I think if you want highest performance, you should avoid regex as it helps to minimize effort, but won't have the best performance as you can almost always adjust code using string routines to a specific problem and gain a big performance boost of it. But for simple parsing routines that can't be optimized much, you can still use regex as it won't make a big difference there.

EDIT: For this specific problem you posted I'd favorize string operations, but only because I wouldn't know how to do it in regex. This seems to be pretty straight-forward, except for the hash, so I think regex/string functions won't make a big difference.

6

I believe there is a threshold from which a regular expression is faster than a bunch of PHP string function calls. Anyway, depends a lot on what you're doing. You have to find out the balance.

Now that you edited your question. I'd use string functions for what you're trying to accomplish. strpos() and substr() is what comes to mind at a first glance.

4

In general, string functions are faster and regex functions are more flexible.

As with anything else, your results may vary, the only way to know for sure is to try it both ways and benchmark.

4

If what you're doing is at all reasonable to do using string functions, you should use them. Like, if you're determining whether a constant string 'abc' occurs in $value, you definitely want to check strpos($value, 'abc') !== false, not preg_match('/abc/', $value). If you find yourself doing a lot of string reshuffling and transformations in order to accomplish what you would've with a regex, though, you're almost certainly going to wind up destroying both performance and maintainability.

When concerned about speed, though, when it comes down to it, don't think about it, clock it. The time command is your friend.

2

I agree with everybody: string functions a a bit more performant, than regex functions. I just wanted to show a small test, that I did in terminal as a proof:

strpos():

$ time php -r '$i = 0; while($i++ < 1000000) strpos("abc", "a");'

real    0m0.380s
user    0m0.368s
sys    0m0.008s

preg_match():

$ time php -r '$i = 0; while($i++ < 1000000) preg_match("/abc/", "a");'

real    0m0.441s
user    0m0.432s
sys    0m0.004s
1

Native string functions are way faster. The benefit of regexp is that you can do pretty much anything with them.

0

Depends on your needs. Most regular expression operations are faster than one would think and can even outperform builtin string functions in certain trivial operations. Note that I have the preg library in mind, not the builtin regex library, which is quite slow.

0

I was searching some information about regex performance - as I need to do a lot of lookups - and truth is that is depends on what you want to achieve. For my purpose I tested one type of searching to compare performance.

Specification: I need to find simple string in array of strings. To test I have $testArray which is array of ~11k multi word phrases build from article about Tolkien (eg. strings "history of the lord of the rings", "christopher tolkien"). As I want to find only phrases containing exact word I cant use strpos() function as eg. when searching for "ring" it would find also phrases with "ringtone" word.

Code using php functions:

$results = array();
$searchWord = 'rings';
foreach ($testArray as $phrase){
  $phraseArr = explode(' ', $phrase);
  if(in_array($searchWord, $phraseArr)){
    $results[] = $phrase;
  }
}

Code using regex function:

$results = array();
$pattern= "/( |^)rings( |$)/";
$results = preg_grep($pattern, $testArray);

I found out in this case regex function was around 10 times faster

Execution times for 100 searches was (using various words)

  • from 0.3436 to 0.3468 second for php functions
  • from 0.0332 to 0.0406 second for regex

Such searching might be trival, but for more complex tasks I assume it would be extremely hard/impossible to implement it without regex just on native php functions.

In conclusion: for simple tasks you should use regex beacuse it would propably be faster, and for complex tasks you propably have to use regex beacuse it would be only way to solve problem.

Edit:

I just realize that this topic is about "PHP string functions" and my test code uses explode() and in_array() functions. So I tried other approach. As my delimiter is space search method below also works and uses strpos() function.

Code using strpos() function:

$results = array();
$searchWord = 'rings';
foreach ($testArray as $phrase){
  if(strpos(' ' . $phrase . ' ', ' ' . $searchWord . ' ')!==FALSE){
    $results[] = $phrase;
  }
} 

But still results was a lot worse than in regex case.

So performance summary is:

  • from 0.3436 to 0.3468 second for php array functions
  • from 0.2001 to 0.2273 second for strpos() function
  • from 0.0332 to 0.0406 second for regex

Still regex is a big winner.

1
  • 1
    Not a fair comparison... you are concatenating 6x per loop. Apr 6, 2020 at 3:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.