Tom
Tom

Reputation: 1628

php - strpos vs preg_match - memory and resource differences

There have been questions asking which is faster strpos or preg_match, but I'm interested which in knowing which uses the least memory and CPU resources.

I want to check a line for one of 5 matches:

if (strpos($key, 'matchA') !== false || strpos($key, 'matchB') !== false || strpos($key, 'matchC') !== false || strpos($key, 'matchD') !== false || strpos($key, 'matchE') !== false) 

if (preg_match("~(matchA|matchB|matchC|matchD|matchE)~i",$key, $match))

What is the best way to do this using the least strain on the server..

Thanks

Upvotes: 1

Views: 102

Answers (1)

Jeff Puckett
Jeff Puckett

Reputation: 41081

Simba's comment is the best answer recommending KCachegrind for application profiling. You can see more about measuring performance in this answer.

For this particular example's question about memory, I measure preg_match being consistently better using PHP's memory_get_peak_usage

<?php
$keys = ['matchA','matchB','matchC','matchD','matchE'];

foreach ($keys as $key)
  preg_match("~(matchA|matchB|matchC|matchD|matchE)~i",$key);

echo 'Peak Memory: '.memory_get_peak_usage();

Peak Memory: 501624

<?php
$keys = ['matchA','matchB','matchC','matchD','matchE'];

foreach ($keys as $key)
  (strpos($key, 'matchA') !== false || strpos($key, 'matchB') !== false || strpos($key, 'matchC') !== false || strpos($key, 'matchD') !== false || strpos($key, 'matchE') !== false);

echo 'Peak Memory: '.memory_get_peak_usage();

Peak Memory: 504624

This seems reasonable to me because you're making 4 extra str_pos function calls.

Upvotes: 1

Related Questions