I was benchmarking constants
vs variables
and noticed a significant improvement of performance when using variables
over constants
. I know it is pretty obvious but it is definietely worth taking into the cosideration that use of local variables over constants whenever possible.
If constants
are being used inside loops
number of times, it is definitely worth declaring the constant as a class / local variable and use it instead.
The benchmarking test case includes creating two functions. Each has a loop that executes 10000000
times. One access a constant declared in a constant file and one access a local variable.
TestConstants.php
class TestConstants
{
const TEST_CONSTANT = 'This is a constant value';
}
Test.php
use TestConstants;
class Test {
protected $TEST_CONSTANT;
protected $limit = 10000000;
function __construct() {
$this->TEST_CONSTANT = 'This is a constant value';
}
function testA() {
$limit = $this->limit;
$time_start = microtime(true);
for ($i = 0; $i < $limit; ++$i) {
TestConstants::TEST_CONSTANT;
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
echo ''. $execution_time .' seconds <br/>';
}
function testB() {
$limit = $this->limit;
$time_start = microtime(true);
for ($i = 0; $i < $limit; ++$i) {
$this->TEST_CONSTANT;
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start);
echo ''. $execution_time .' seconds <br/>';
}
}
$test = new Test();
$test->testA();
$test->testB();
Results are as follows
testA() executes in 0.55921387672424 seconds
and
testB() executes in 0.33076691627502 seconds
PHP Version
5.6.30
I thought to share this as someone out there might be benefitted by avoiding direct calls to constants
(especially inside loops) by declaring them as variables
wherever applicable.
Thank you.