The Speed Of String Comparison Functions In PHP
Published January 7th, 2007 in SoftwareSometimes it seems like everyone has a different opinion on something, and the best function for comparing simple strings in PHP is one of those things. The four primary ways are ereg(), preg_match(), strstr(), and strpos(). For a simple comparison, any of these will work, but, once you start doing a great deal of string comparison, the speed of these functions comes into play. Even the PHP site suggests preg_match() on the ereg() page:
Note: preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().
Then, if you check the preg_match() page, it says:
Tip: Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.
I decided the best answer was to test each one and see what I came up with.
My test was to search for a five character string within a string of approximately 60,000 characters. The test was originally going to run 10,000 times, but I ended up doing that 25 times for each function, taking the average in order to try to limit variation.
| Results | |
| ereg | .956 |
| preg_match | .050 |
| strstr | .222 |
| strpos | .033 |
Occasionally, preg_match() would come very close to beating strpos(), but overall the results showed strpos() to be the fastest, followed closely by preg_match(), then strstr(), and pulling up the rear was ereg(). It looks like strpos() is definitely the best function for a quick check, and preg_match() is the answer for any searches that require a little more sophistication, but the differences were minimal. Keep in mind, these results represent 10,000 searches of a nearly 60,000 character string. Most applications/scripts would never come close to that, so the function choice isn’t a major concern.
2 Responses to “The Speed Of String Comparison Functions In PHP”
- 1 Pingback on Nov 28th, 2007 at 5:09 pm


This is the great article very useful for writing optimized code.