My current web application uses about 30 or so Contants (DEFINE()). I am reading things that variables are quicker. Provided that there is a naming convention to avoid variable overwrites, the only other draw back I see is that these variables would have to be defined as global variables some how in every function.
Which is faster? I use these constants a whole lot throughout my application and will probably be forever adding more to the list and they are used in and out of functions and classes.
A quick test showed that defining constants ( define('FOO', 'bar'); ) is about 16 to 18 times slower than defining a variable ( $foo = 'bar'; ), but using the defined (constant) value is about 4 to 6 times faster.
No, const does not help the compiler make faster code.
Constants defined using define()
are fairly slow in PHP. People actually wrote extensions (like hidef) to improve the performance.
But unless you have loads of constants this shouldn't make much of a difference.
As of PHP 5.3 you can also use compile-time constants using const NAME = VALUE;
. Those are much faster.
The difference would be really small (micro optimizations). You would better encapsulate some of your constants in classes so you can access them by Classname::CONSTANT
to not pollute the global namespace of your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With