PHP App Configuration : define or not define
I have seen quite a few PHP apps with hundreds of defines. Those are generally loaded on each request, and when every tuning has already been done, those define can amount to a significant proportion of the PHP execution time. Here is a little benchmark :
4 different scripts are tested :
[...]
define(’DEFINEXXX’, XXX);
[...]
[...]
@define(’DEFINEXXX’, XXX);
[...]
[...]
if (!defined(’DEFINEXXX’)) define(’DEFINEXXX’, XXX);
[...]
Each line is repeated 500 times with XXX ranging from 0 to 499.
| 500x define() | 0,7 ms |
| 500x @define() | 1,0 ms |
| 500x if (!defined()) | 1,4 ms |
Let’s think a little bit. defined is resolved at execution time. Could we have something that would be resolved at compilation time (and cached by an opcode cache) ? What if we used a class with a lot of const attributes :
class Config {
[...]
const DEFINEXXX = XXX;
[...]
}
The const DEFINEXXX is again repeated 500 times, from 0 to 499.
Execution time is now 0,01 ms. Great !
The conclusion
Avoid defines, use const attributes !