Hi everybody, When I re-use an unchanging variable 3 or more times in a script, would it be faster to use a variable or a constant? Thanks, -Tony
Uhm... no. Not even CLOSE... There are advantages and disadvantages, but I would never go so far as to call them 'inefficient' when the byte-code compiler should be practicing "constant folding" (putting the value in the code instead of calling it from variable space). Usually that means constants use less memory and execute faster. (this is more true in compiled languages) That they are set once and then cannot be deleted or changed is great for security status values or status flags, as well as setting up things like conditional compilation. That they are global in scope also means they are great for storing repeatedly used values you might want to change en-masse. The disadvantages are, as ThePHPMaster suggested that they are global in scope so anything set in them is accessible EVERYWHERE, and you have to concern yourself with the possibility of namespace conflicts (which practicing a naming convention can easily avoid) and that certain values you don't want "every bit of code" to have access too reading don't belong in them. See the asshattery in wordpress of putting the mysql username and password in defines... the pinnacle of "security, what's that?" But also, you have to remember PHP now has CLASS constants -- declared with CONST they are local to that object, which is why to use them elsewhere you have to use the CONSTANT function. "Less efficient"?!? No... They're just different and another tool in the toolbox -- just keep in mind "The right tool for the right job" and you'll be fine.
I guess I phrased my answer in the wrong way. I just meant to answer the question if it is faster or not. I meant that using variables is faster than using constants in his case. I setup a test case of a simple script with usage of three variables and one with three constants, the one with three variables was 0.008 seconds faster. I also looked up some people who did the same tests who achieved the same results. But you are correct, at many times using constants can prove to be faster than variables, it all depends on a use by use cases.