PHP 5.4 Object Property Optimization

Posted by david on 14 June 2012 at 12:01 pm

There is an interesting article on the PHP Classes blog about an optimization that was introduced in PHP 5.4. I remember reading about a change to the way PHP 5.4 handles object properties, but I don't remember it explaining what the optimization did. 

"That was when Portuguese core developer Gustavo Lopes explained that starting PHP 5.4 the dynamic properties hash table is created only if variables are added dynamically to objects at runtime."

This is quite interesting and kind of surprises me that it wasn't in PHP 5 already. What the quote means is if you only use object properties that you declare in the class declaration (before using the properties in a method), PHP 5.4 uses a single hash table for any object created from the class. In the past PHP 5 created a new hash table for every object, which meant if no dynamic properties were introduced after the class declaration it was wasting memory on excess hash tables it never really needed.

This explains the phantom memory differences between my web server (PHP 5.4.x) and my test server before I upgraded it to PHP 5.4. Lesson learned: Declaring class properties isn't only to make the code easier to read, it's also an optimization!


Log in to comment

No comments yet!