Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress the_permalink performance vs Storing the value in a variable

What could be the most efficient way to make a new Theme and create an article view with multiple objects that link to said article? I am a C# pro but in PHP I am not as well versed as I wish I was. Suppose you have:

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>

As you can see we have at least 3 calls to the function the_permalink();

Is it faster to call the function three times, or rather call it one time, save it in a variable, and then throw the variable within the loop as much as needed?

like image 635
Luis Robles Avatar asked Dec 05 '25 03:12

Luis Robles


2 Answers

While there would be less CPU load to do this, it's a case of premature optimization. The benefit you get isn't that great, particularly because this call doesn't have to touch the database. Once you factor in the fact that what takes the longest with PHP is compiling the code, I'd be surprised if you saw any benefit in a benchmark.

If you dig into the get_permalink() function (in wp-includes/link-template.php) you'll note that the method only consults the options store, which is loaded once on WP initialization.

If you're trying to speed up the site, 99% of the time the way to do it is to cut down on database calls. I'd focus your efforts there :)

like image 101
Jeremy Massel Avatar answered Dec 06 '25 17:12

Jeremy Massel


I was curious, so I benched with the following code:

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>';

And got the following result:

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

So storing in a variable and echoing is substantially faster if there are a large number of calls, but for just three calls the performance improvement is only going to be a bit more than one one-thousandth of a second.

Note that some filters are called every time you call the_permalink() too (e.g. the_permalink, post_link, etc.) so the speed gain from storing in a variable may be higher depending on how many hooks there are into those filters and what they do.

like image 22
AlliterativeAlice Avatar answered Dec 06 '25 18:12

AlliterativeAlice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!