tags:

views:

152

answers:

2

When querying data via PHP, will it significantly slow down the page loading time if I can the items separately?

For example, pulling in three items at a time:

<?php foreach ($example->get_items(0,3) as $item): ?>

Versus call each of the separately:

<?php foreach ($example->get_items(0,1) as $item): ?>
<?php foreach ($example->get_items(0,1) as $item): ?>
<?php foreach ($example->get_items(0,1) as $item): ?>
+3  A: 

If you're asking if the overhead of three sequential loop structures versus one on the exact same data or looping on 3-4 items versus calling them individually will impact page performance, the answer is no.

Excessive code, round trips to other servers, etc will impact page performance. Inadequate caching will impact page performance. But statement and function call overhead (unless you're well in the tens of thousands) is micro-optimization and an irrelevant distraction.

So if you're selecting a single row at a time from a query and executing that query a hundred times then changing that query to be called once but return all hundred rows then that's the sort of thing that will make a difference.

But don't sweat the small stuff like this, if/else vs switch and other than micro-issues. Worry more about readability and correctness.

cletus
Very helpful -- thanks.
A: 

Loops will always slow down your page load, however I don't believe the difference between looping and manually calling each of the 3 items will be noticeable.

I would go with the approach that makes your code cleaner:

<?php foreach ($example->get_items(0,3) as $item): ?>
Alix Axel
Ooops .. accidentally downvoted. (Don't ask me how lol)
Chacha102
@Chacha102: I'm still beating you! :P
Alix Axel
@Alix You won a bounty or something. But at least I'm in the top 30 PHP Answerers :)
Chacha102