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

2
  • You could, of course, write a benchmark program to find out for yourself. :) Commented Jul 1, 2016 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. Commented Jul 1, 2016 at 13:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.