Do constants take less memory ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Do constants take less memory ?

Post 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
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post 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.
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post 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.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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.
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post 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.
Post Reply