We can assign values to constant or variables. Which one is better from a memory and optimization point of view?
define("X",5);
or
$x = 5;
Does in both case integer occupy same memory? Which one take more memory space and faster to run?
I have analyzed this task 100k times in php.exe on command prompt and explaining here...
//Defining a constant Test
$DefConst_TimeStart = microtime();
$DefConst_MemStart = memory_get_usage();
for($i=1;$i<=100000;$i++){
define("x$i",$i);
}
$DefConst_MemEnd = memory_get_usage();
$DefConst_TimeEnd = microtime();
//Variable test
$Variable_TimeStart = microtime();
$Variable_MemStart = memory_get_usage();
for($i=1;$i<=100000;$i++){
${"x".$i} = $i;
}
$Variable_MemEnd = memory_get_usage();
$Variable_TimeEnd = microtime();
//Output of the results
echo "Define Constant: Time: ".($DefConst_TimeEnd - $DefConst_TimeStart)." ms | Memory: ".($DefConst_MemEnd - $DefConst_MemStart)." Bytes\n";
echo "Setting Variable: Time: ".($Variable_TimeEnd - $Variable_TimeStart)." ms | Memory: ".($Variable_MemEnd - $Variable_MemStart)." Bytes\n";
And according to analysis:
Time taken: Variable is faster in execution rather than constant
Memory usage: Constant occupy less memory than variable
Output image
You can download file from github to test it
Benchmark example to test speed and memory usage
let me know am i on right track or not?