admin管理员组文章数量:1318027
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
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
Share Improve this question edited Nov 1, 2020 at 6:22 Botond Vajna asked Nov 1, 2020 at 6:11 Botond VajnaBotond Vajna 4714 silver badges11 bronze badges1 Answer
Reset to default 2Your 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.
本文标签: phpIt is a good idea to store values from the global post if they are used multiple times
版权声明:本文标题:php - It is a good idea to store values from the global $post if they are used multiple times? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742022530a2414942.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论