TransWikia.com

It is a good idea to store values from the global $post if they are used multiple times?

WordPress Development Asked by Botond Vajna on January 4, 2021

I am wandering if it is a good idea to store values from the global $post if they are used multiple times like in the example below, or is having no effect on performance?

$post_id = $post->ID; 
echo get_the_title($post_id);
echo get_the_post_thumbnail_url($post_id);

// or

echo get_the_title($post->ID);
echo get_the_post_thumbnail_url($post->ID);

My thought is that in the second example, it must query the global $post every time, while in the first just once, and this may affect the performance.

Thank you

One Answer

Your first example with a separate variable is actually slower. In both cases you have the $post variable already in your scope, and reading from that doesn't cost anything. But if you create a copy and assign that to a new variable, you are using more resources. Just reading an existing variable doesn't cost any time.

In real life, it doesn't matter. The difference is so small that you probably can't even see it in performance tests unless you do that with thousands of different variables at the same request.

What you should go for is readability. Using $post->ID makes it a bit easier to see where that value is coming from than with $post_id. In an IDE you can click on the $post part of $post->ID and get some information about this object, like the other variables and maybe available methods.

Answered by fuxia on January 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP