Does using static methods and properties in PHP use less memory?

T. Brian Jones picture T. Brian Jones · Oct 19, 2012 · Viewed 8.7k times · Source

I'm working on a web application that sees dozens of concurrent users per second. I have a class that will be instantiated many times within the same page load. In that class, I have some properties that will always be the same across every object, so I'm thinking about declaring these properties as static in an effort to reduce the memory that will be used when multiple instances of this class are instantiated during the same page request.

Will doing this use less memory for this application because PHP can store the value of the static properties only once? Will doing this save memory across concurrent users, or just within each PHP process?

How does this work for methods? If this means objects can recycle the same methods, then why wouldn't all methods of a class be declared static if you are trying to save on memory?

I don't feel entirely comfortable with why and when one would declare a property or method static, but I do understand that declaring them as static allows them to be accessed without instantiating an object of the class ( this feels like a hack ... these methods and properties should be somewhere else ... no? ). I'm specifically interested in the way a static declaration affects memory usage in an effort to keep memory usage as low as possible on my web server ... and in general so I have a better understanding of what is going on.

Answer

raidenace picture raidenace · Oct 20, 2012

When you declare a class method/variable as static, it is bound to and shared by the class, not the object. From a memory management perspective what this means is that when the class definition is loaded into the heap memory, these static objects are created there. When the class's actual object is created in the stack memory and when updates on the static properties are done, the pointer to the heap which contains the static object gets updated. This does help to reduce memory but not by much.

From a programming paradigm, people usually choose to use static variables for architectural advantages more than memory management optimization. In other words, one might create static variables like you mentioned, when one wants to implement a singleton or factory pattern. It provides more powerful ways of knowing what is going on at a "class" level as opposed to what transpires at an "object" level.