0

I am trying to optimize a function that is called 560x during the execution of a request.

The function is this (some info redacted):

function foo($text) {
    if (preg_match('/[`"]/', $text)) {
        throw new Exception("very detailed error");
    }
    $text = explode('.', $text);
    $tick = '*';
    return $tick . implode("$tick.$tick", $text) . $tick;
}

Using XDEBUG PHP profiler + Webgrind, I see that these stats (in milliseconds) for this function: enter image description here

As you can see, only 3ms is spent in preg_match, explode, implode combined. The other 20ms is spent just invoking these functions and concatenating some string. Is there a way I can reduce the total self cost of this function?

I have tried adding

use function preg_match;
use function explode;
use function implode;

as suggested here, but I did not see any improvements. Any suggestions?

Moe Sanjaq
  • 25
  • 6
  • If 87% of the time is spent _invoking_ the function, why are we looking at the function? I would consider ways to avoid calling the function at all. – Rick James Aug 05 '20 at 03:02

1 Answers1

0

Consider switching to a more light-weight functions (but maybe losing some readability):

function foo($text) {
    if (strpos($text, '"')!==FALSE || strpos($text, '`')!==FALSE) {
        throw new Exception("very detailed error");
    }
    $tick = '*';
    return $tick . str_replace('.', "$tick.$tick", $text) . $tick;
}
Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
  • Although logically this should decrease the latency, since it gets rid of the regex, it actually increases in practice by ~3ms it since there is an additional function call. There is a fixed-cost to a function call, other than the complexity of the actual function. This fixed cost is where most of the latency is coming from – Moe Sanjaq Aug 05 '20 at 01:18