最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

发布评论

评论列表(0)

  1. 暂无评论