Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

Is there a benefit to using a calculated value in a PHP constant?

I reviewed code that contains the following expression:

const COLOR_MAX = (2 << 7) - 1;

I know that the OP has some experience with other languages like and where such operations are more common and may have benefits for performance or other aspects.

In terms of memory or processing time is there any advantage to defining the constant using the calculated value after the bit-shift and subtraction, or would it be simple enough to just use the value:

const COLOR_MAX = 255;

I tried comparing the execution time and memory usage of both examples:

<?php 
$start = hrtime(true);
const COLOR_MAX = (2 << 7) - 1;
//const COLOR_MAX = 255;
$eta = hrtime(true) - $start;
$memUsage = memory_get_usage();
echo 'end: '.($eta / 1e+6).' memory usage: '.$memUsage . PHP_EOL;

Results for bit-shifted, run three times:

end: 0.003254 memory usage: 392136
end: 0.003289 memory usage: 392136
end: 0.00338 memory usage: 392136

Results for the static value, run three times:

end: 0.003421 memory usage: 392136
end: 0.003095 memory usage: 392136
end: 0.003705 memory usage: 392136

Any differences in memory or execution time appear to be negligible.

Note: Tested using PHP 7.4.6.

Upvotes: 0

Views: 328

Answers (2)

Sammitch
Sammitch

Reputation: 32232

It's a constant value, not a compiler macro. It will be evaluated exactly once when the class file is parsed, and the amount of time/resources required to do so are so small as to be within the margin of error even if you were to benchmark millions or billions of iterations.

There is no consequential result of doing it one way or another beyond the preferences of the meat sack reading/writing the code.

Upvotes: 0

Martheen
Martheen

Reputation: 5580

Even in C, it's not really about optimization, since const will be calculated on compile time. Using bit-shifting instead of typing the literal help remind "this will be using this many bit, occupying this slot", useful if there's going to be plenty of bitwise operation such as cramming multiple values in one byte (or in PHP case, in a single variable)

Upvotes: 1

Related Questions