Reputation: 8113
Particularly in wordpress, I was wondering: does it make sense saving for example $post->ID
into a $post_id
variable when accessing it several times from a loop?
I mean: $post_id = $post->ID
Then always call $post_id
when needed in functions.
I basically find myself doing it all the time, because in javascript you save memory. But is it true in this php/wordpress context too?
Upvotes: 5
Views: 278
Reputation: 15374
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.
Upvotes: 6