第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

提高現(xiàn)有功能的性能,Laravel

提高現(xiàn)有功能的性能,Laravel

PHP
滄海一幻覺 2023-04-28 16:30:52
我嘗試重構我的代碼,但我的代碼表現(xiàn)不佳。目標是獲得具有 unique 的數(shù)組列表"answer_id",并獲得一些“分數(shù)”、“投票”等。在我現(xiàn)有的元素中,我首先檢查 $most_voted 是否為 null,如果是,我分配第一個元素,然后我將在第二個元素中插入一個foreach新元素,或者我更新一個現(xiàn)有元素。但是從我的第二個開始foreach,我就過得很糟糕。關于這個邏輯有什么建議嗎?$answers = $history->toArray(); //here I have an array of arrays$most_voted = [];foreach ($answers as $key => $answer) {    if (!empty($most_voted) ) {        // in this if I create new arrays or I update existing ones         foreach ($most_voted as $k => $v) {            //If value already exists, increase Votes/Score/Percentage            if (intval($most_voted[$k]['answer_id']) === intval($answer['lkp_answer_id'])) {                $most_voted[$k]['Votes'] = $most_voted[$k]['Votes'] + 1;                $most_voted[$k]['Score'] = $most_voted[$k]['Score'] + $answer['score'];                $most_voted[$k]['Percentage'] = substr((($most_voted[$k]['Votes'] * 100) / $votes), 0, 5);                $most_voted[$k]['Weight'] = substr((($most_voted[$k]['Score'] * 100) / $total_scoring), 0, 5);                //Else add new array element            } else {                $name = LkpAnswer::where('id', '=', $answer['lkp_answer_id'])->pluck('name');                (isset($name[0]) && $name[0] !== null) ? $name = $name[0] : '';                                if(! empty($answer['lkp_answer_id'])){                    $most_voted[$key] = [                        'answer_id' => $answer['lkp_answer_id'],                        'Name' => $name,                        'Votes' => 1,                        'Score' => $answer['score'],                        'Percentage' => substr(((1 * 100) / $votes), 0, 5),                        'Weight' => substr((($answer['score'] * 100) / $total_scoring), 0, 5),                    ];                }            }        }    } 
查看完整描述

1 回答

?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

優(yōu)化的第一條規(guī)則(在我看來),


切勿在循環(huán)內運行查詢。


在循環(huán)開始之前:


// Fetch all data at once and use select() whenever possible

$LkpAnswers = LkpAnswer::whereIn('id', collect($answers)->pluck('lkp_answer_id')->toArray())->select('name')->get();


在你的其他條件下(在第二個循環(huán)內)做這樣的事情。


// Before, this query was inside 2 for loops (n^2). For every n, there's 1 query.

// This right here is a Collection of LkpAnswer::model. Collection is very useful for optimization

$name = $LkpAnswers->where('id', $answer['lkp_answer_id'])->pluck('name')->toArray();

使用它并更改您的第二個 else 條件。僅通過這樣做,您將減少近 50% 的運行時間。另請查看有關如何在 laravel 中進行優(yōu)化的答案。它討論了緩存、索引、select()和類型轉換。


讓我在下面的評論中發(fā)布。


查看完整回答
反對 回復 2023-04-28
  • 1 回答
  • 0 關注
  • 98 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號