My page takes 3-5 whole minutes to load, how can I possibly reduce it?

我与影子孤独终老i 提交于 2019-12-11 07:06:45

问题


I'm currently working on this project and the main page takes nearly 5 whole minutes to load. I've been trying to reduce the runtime, but I'm still new to programming and I'm not too familiar with pthreads, but I was told pthreads wouldn't work with this. Can someone help me figure out how to run this code faster and stop Chrome from killing the processor?

Also I know my PHP code is a bit messy, was planning on cleaning it up later, but the little bits of PHP code are around lines 0, 270, 420, 560, etc throughout the entire page.

Thank you for your time.

Here's a snippet of the code, but you can find the entire code in the pastebin linked below:

<?php $k = 0; ?>

<tr>
    @foreach($mondays as $monday)
    <?php $shift_worker_id = DB::table('schedule')->where('id', $monday->id)->value('shift_worker_id') ?>
    <?php $zone_id = DB::table('schedule')->where('id', $monday->id)->value('zone_id') ?>
    <?php $zone = DB::table('zone')->where('id', $zone_id)->value('name') ?>
    <?php $worker_id = DB::table('shift_worker')->where('id', $shift_worker_id)->value('worker_id') ?>
    <?php $shift_id = DB::table('shift_worker')->where('id', $shift_worker_id)->value('shift_id') ?>
    <?php $time = DB::table('shift')->where('id', $shift_id)->value('time') ?>
    <?php $type = DB::table('shift')->where('id', $shift_id)->value('type') ?>
    <?php $name = DB::table('worker')->where('id', $worker_id)->value('name') ?>
    @if($type == "Graveyard")
        <th style="font-size:11px" colspan="1">{{$name}}</th>
        <th style="font-size:7px" colspan="1">{{$time}}</th>
        <th style="font-size:11px" colspan="1">{{$zone}}</th>
        <th colspan="1"></th>
        <th colspan="1"></th>
        <th colspan="1"></th>
        <?php $k++; ?>
    @endif
    @if($k % 4 == 0)
        </tr>
        <tr>
    @endif
    @endforeach
</tr>

https://pastebin.com/uUGrs1x0


回答1:


It's definitely because of N+1 problem. Learn how to use eager loading.

You're creating a lot of redundant queries to the DB inside the loop, probably thousands instead of just 6.

Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.

https://laravel.com/docs/5.5/eloquent-relationships#eager-loading



来源:https://stackoverflow.com/questions/46877277/my-page-takes-3-5-whole-minutes-to-load-how-can-i-possibly-reduce-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!