If it was me, I’d run tests to find out which one is actually slower. This may mean doing the same process 100 or 1000 times to see time differences, but that’s the only way to actually know which is better.
As a complete guess, I’d say that a for loop with get_posts woudl be faster, but that will depend on how you have your output, templates, and more set up.
Thread Starter
Jim
(@kernix)
Assuming I even knew how to do a test (which I don’t), I wouldn’t even do 10 let alone 100. It’s a recent posts query for a cat at the bottom of the front page – the get_posts is right after the get_template_part and before the endwhile, and the WP_Query is outside of that though I could move that to the same place as well.
In your case I would avoid optimizing for nanoseconds and focus the attention elsewhere to build something awesome 🙂
Just pick one! It doesn’t sound like you are building a massive web app to handle tens of millions of requests per second here.
And for what it’s worth, get_posts still instantiates the WP_Query class:
https://developer.wordpress.org/reference/functions/get_posts/#source
So you’re basically doing a WP_Query either way.
Thread Starter
Jim
(@kernix)
Ok, maybe I’ll stick with my original wp_query then – thanks
I haven’t seen the code, but do what is easiest to read and maintain. Don’t over optimize just for the sake of optimizing. And don’t fix it if it ain’t broke! 😀
Dekadinious sounds like the voice of hard won experience 🙂 Unless your site is going to grow into many thousands of posts, there may be no noticeable difference. You can use your browser’s network developer tool to see overall timing of each request. Address any significantly long requests that you have control over, don’t worry about things that take a reasonable time or you cannot control. There are more focused performance measures, but they’re not worth getting into.
Further confusing theoretical performance statistics is WP will often cache some query results, so performance depends on whether the cache had been primed or not. As has been pointed out, get_posts() is really just a wrapper for WP_Query, so which you use makes little difference.
What can make a difference is limiting how many queries are made overall. If you need the query results sorted in a particular order, SQL will be faster than PHP for any given single query. But some sort criteria may be easier to achieve through PHP and the difference can be negligible unless a huge number of posts are involved.
Discussion of which is more efficient can make for interesting conversation among coding geeks, but there is rarely much real world difference in results.
Thread Starter
Jim
(@kernix)
@bcworkz Got it. It’s just one query on front-page.php so I decided to go with get_posts inside the loop, though I 3rd method I saw in a video by WPCasts was to use SQL and $wpdb. Maybe I’ll try that one at a later time.