Wordpress the_permalink performance vs Storing the value in


Wordpress the_permalink performance vs Storing the value in a variable

制作一个新主题并创建一个包含多个链接到所述文章的对象的文章视图的最有效方法是什么?我是一名C#专业人士,但在PHP方面我并不像我希望的那样精通。假设你有:

while(have_posts())
    <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
    <a href="<?php the_permalink(); ?>"><?php the_thumbnail(); ?></a>
    <a href="<?php the_permalink(); ?>">read more</a>

正如您所看到的,我们至少有3个对函数the_permalink(); 的调用

调用该函数三次,或者更确切地说,调用一次,将其保存在变量中,然后根据需要在循环中抛出变量,这样会更快吗?

虽然这样做会减少CPU负载,但这是一种过早优化的情况。你得到的好处并不是很大,特别是因为这个调用不必接触数据库。一旦你考虑到PHP耗时最长的是编译代码,如果你看到基准测试的任何好处,我会感到惊讶。

如果深入研究get_permink()函数(在wp-includs/link-template.php中),您会注意到该方法只参考选项存储,它在wp初始化时加载一次。

如果你想加快网站的速度,99%的方法是减少数据库调用。我会把你的工作重点放在那里:)

我很好奇,所以我用以下代码进行了测试:

ob_start();
$bench = microtime(true);
for ($i = 0; $i < 1000; ++$i) {
    the_permalink();
    the_permalink();
    the_permalink();
}
$bench2 = microtime(true);
ob_end_clean();
echo ($bench2 - $bench) . '<br>';
ob_start();
$bench = microtime(true);
for ($i = 0; $i < 1000; ++$i) {
    $permalink = get_permalink();
    echo $permalink;
    echo $permalink;
    echo $permalink;
}
$bench2 = microtime(true);
ob_end_clean();
echo ($bench2 - $bench) . '<br>';

并得到以下结果:

the_permalink(): 1.891793012619
Storing in a variable and echoing: 0.62593913078308

因此,如果有大量调用,存储在变量中并进行回显会快得多,但对于仅三次调用,性能的提高只会略高于千分之一秒。

请注意,每次调用_permink()时也会调用一些过滤器(例如_permink、post_link等),因此存储在变量中的速度增益可能会更高,这取决于这些过滤器中有多少钩子以及它们的作用

将其存储在一个变量中肯定比根据您的示例连续调用它3次要少得多的后端处理。由于_permink()会回显permalink,因此必须使用get_permlink()将其存储在变量中。

<?php
while(have_posts()) {
    $permalink = get_permalink();
?>
<h4><a href="<?php echo $permalink; ?>"><?php the_title(); ?></a></h4>
<a href="<?php echo $permalink; ?>"><?php the_thumbnail(); ?></a>
<a href="<?php echo $permalink; ?>">read more</a>