PHP: How to make INVOKING internal functions faster

99 views Asked by At

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?

1

There are 1 answers

1
Alberto On

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;
}