1

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

Tom
  • 1,436
  • 24
  • 50
  • You could, of course, write a benchmark program to find out for yourself. :) – Simba Jul 01 '16 at 13:16
  • 1
    However, if you're worried about this because you want to optimise your code, my main recommendation would be letting it rest and just going with the one that is easiest to read / understand / debug / maintain. Unless you're doing it in a loop with thousands of iterations, there simply won't be a performance difference to measure so optimising it won't make any difference. If you're looking to optimise your code, start by using a tool like KCacheGrind to find out the specific bottlenecks in your code. Those are the bits you need to optimise first. – Simba Jul 01 '16 at 13:16

1 Answers1

1

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.

Community
  • 1
  • 1
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167