简体   繁体   中英

Will multiple “foreach” queries in PHP slow down the page load?

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): ?>

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.

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): ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM