Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster? Constants, Variables or Variable Arrays

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.

like image 839
David Avatar asked Oct 14 '11 10:10

David


People also ask

Are constants faster than variables?

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.

Do constants make a program faster?

No, const does not help the compiler make faster code.


2 Answers

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.

like image 94
NikiC Avatar answered Sep 21 '22 00:09

NikiC


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.

like image 36
str Avatar answered Sep 22 '22 00:09

str