3

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

enter image description here

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?

Yadav Chetan
  • 1,874
  • 2
  • 23
  • 43
  • i have gone through that question but i could not get exact answer regarding memory optimization – Yadav Chetan Aug 11 '15 at 05:17
  • 1
    I tried benchmarking a simple constant vs. variable but there's a limit to online tools. [Constant Bench](http://3v4l.org/6KVGh/perf#tabs) vs. [Variable Bench](http://3v4l.org/V7VAY/perf#tabs) – iDev247 Aug 11 '15 at 05:40

2 Answers2

2

The difference between assigning a single variable and defining a single constant is likely to be so tiny that it would be dwarfed by random variation in the rest of the program.

Both are high-level constructs registering an association between a name and a value in a complex type structure, subject to all sorts of optimisations and special cases in the underlying engine.

If you had hundreds of such definitions, you might begin to notice a small difference, but at that point there's something wrong with the design of your program.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
1

I would prefer using the Variable simply because declaring the variable itself doesn't need to call a function while define is a function that will define a value.

jameshwart lopez
  • 2,993
  • 6
  • 35
  • 65