Page 1 of 1

Do constants take less memory ?

Posted: Thu Aug 16, 2007 3:01 pm
by anjanesh
Hi

I currently have my configuration settings such as database username, password, absoulte-path etc stored in an array.
But will changing everything to constants take less memory ? Im not too worried abt it being modified but constants take less memory, then its worth the switch.
Referring to constants of define() type and class constants.

Thanks

Posted: Thu Aug 16, 2007 3:39 pm
by Begby
Even if constants took up 1/100 the memory of a variable its not worth switching just for memory's sake as in the grand scheme of things that will be insignificant in all but heavily used applications. First and foremost your code needs to be easy to maintain and readable. I would buy a new server before I started switching variables to constants to save memory.

If for some reason you have thousands of variables and its eating up memory, then something is wrong with how you are coding.

Posted: Thu Aug 16, 2007 3:42 pm
by anjanesh
I have a long list of configuration settings - all in one giant array tree - was thinking of switching them to constants if it made sense to save that much array memory.

Posted: Thu Aug 16, 2007 5:37 pm
by superdezign
Constants in the define() sense don't save any memory at all. Global data is global data and, as far as I know, you cannot deallocate that memory until the script is complete. On the other hand, using class constants allows you to destroy the class. I'm not too familiar with the inner workings of PHP as I haven't had the time nor motivation to really go deeper, but worrying about optimization at that level is, frankly, foolish. The data still needs to be allocated, and will do so on *every*page*request* regardless of how you initialize it. Constants should be the least of your concerns.

Posted: Thu Aug 16, 2007 7:10 pm
by stereofrog
Unlike say C, php doesn't resolve constants at compile time, so they take up memory at runtime.
That said, I agree with others - this doesn't make any practical difference.