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:
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?
Consider switching to a more light-weight functions (but maybe losing some readability):