PHP is a very popular scripting language, used on many popular sites across the web. In this article, we hope to help you to improve the performance of your PHP scripts with some changes that you can make very quickly and painlessly. Please keep in mind that your own performance gains may vary greatly, depending on which version of PHP you are running, your web server environment, and the complexity of your code.

<?php

// Avoid writing naive setters and getters
//
// When writing classes in PHP, you can save time and
// speed up your scripts by working with object properties
// directly, rather than writing naive setters and getters.
//
// In the following example, the dog class uses the setName() and
// getName() methods for accessing the name property.
class dog
{

    public $name = '';

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}

// SLOW
$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

// FAST
$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

// Profile via CLI
//
// Setting and calling the name property directly can
// run up to 100% faster, as well as cutting down on development time.
//
// php -d implicit_flush=off -r 'class dog {public $name = "";public function setName($name) {$this->name = $name; }public function getName() {return $this->name; } }$rover = new dog();for ($x=0; $x<10; $x++) { $t = microtime(true);for ($i=0; $i<1000000; $i++) { $rover->setName("rover");$n = $rover->getName();}echo microtime(true) - $t;echo "\n";}'
//
// php -d implicit_flush=off -r 'class dog { public $name = "";} $rover = new dog(); for ($x=0; $x<10; $x++) { $t = microtime(true); for ($i=0; $i<1000000; $i++) { $rover->name = "rover"; $n = $rover->name;} echo microtime(true) - $t;echo "\n";}'

// or Profile via web script

// SLOW
class dog
{

    public $name = "";

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}
$rover = new dog();
for ($x = 0; $x < 10; $x ++)
{
    $t = microtime(true);
    for ($i = 0; $i < 1000000; $i ++)
    {
        $rover->setName("rover");
        $n = $rover->getName();
    }
    echo microtime(true) - $t;
    echo "n";
}

// FAST

class dog
{

    public $name = "";
}
$rover = new dog();
for ($x = 0; $x < 10; $x ++)
{
    $t = microtime(true);
    for ($i = 0; $i < 1000000; $i ++)
    {
        $rover->name = "rover";
        $n = $rover->name;
    }
    echo microtime(true) - $t;
    echo "n";
}