Sunday, May 20, 2007

php performance (code)

require_once "./a.php";
require_once "a.php";

php_version() = PHP_VERSION constant
php_uname(‘s’) = PHP_OS constant
php_sapi_name() = PHP_SAPI constant

// Slow
if (preg_match("!^foo_!i", "FoO_")) { }
// Much faster
if (!strncasecmp("foo_", "FoO_", 4)) { }

// Slow
if (preg_match("![a8f9]!", "sometext")) { }
// Faster
if (strpbrk("a8f9", "sometext")) { }

// Slow
if (preg_match("!string!i", "text")) {}
// Faster
if (stripos("text", "string") !== false) {}

$text = preg_replace( "/\n/", "\\n", $text);
In this case it would be simpler and to mention faster to use a regular str_replace()
$text = str_replace( "/\n/", "\\n", $text);

$rep = array( '-' => '*', '.' => '*' );
if ( sizeof( $globArr ) > 1 ) {
$glob = "-" . strtr( $globArr[1], $rep );
} else {
$glob = strtr( $globArr[0], $rep );
}
if ( sizeof( $globArr ) > 1 ) {
$glob = "-" . strtr( $globArr[1], '-.', '**' );
} else {
$glob = strtr( $globArr[0], '-.', '**' );
}

// The Good
if (!strncmp(PHP_OS, 'WIN', 3)) {
if (!strncasecmp(PHP_OS, 'WIN', 3)) {
// The Bad
if (substr(PHP_OS, 0, 3) == 'WIN') {
if (strtolower(substr(PHP_OS, 0, 3))) == 'win') {
// And The Ugly
if (preg_match('!^WIN!', PHP_OS)) {
if (preg_match('!^WIN!i', PHP_OS)) {

if (substr($class, -15) != 'text')
/* == */
if (substr_compare($class, 'text', -15))


References can be used to simply & accelerate access
to multi-dimensional arrays.
$a['b']['c'] = array();
// slow 2 extra hash lookups per access
for($i = 0; $i < 5; $i++)
$a['b']['c'][$i] = $i;
// much faster reference based approach
$ref =& $a['b']['c'];
for($i = 0; $i < 5; $i++)
$ref[$i] = $i;

all info from slides and other sources Ilia Alshanetsky

No comments:

Post a Comment