Is it worth saving an object property into a variable when accessed several times? Is it worth saving an object property into a variable when accessed several times? wordpress wordpress

Is it worth saving an object property into a variable when accessed several times?


In modern PHP adding the $post_id variable will have almost no memory impact if it's only read for loops. The value of the two variables is referenced in one memory location until you modify one of the variables, at which time PHP copies it into two separate places in memory. This is referred to as copy-on-write.

The only difference in performance might be dereferencing the object property. The cost, if any, is so small it's negligible.

So to answer your original question, no it's not worth adding another variable to gain performance. Also see this broad conversation on micro-optimization.