php導致記憶體溢位
阿新 • • 發佈:2018-12-19
在執行一個匯出csv腳步時,當要匯出的資料超過3w多條時,就會報錯,如下:
Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
php儲存3w多條資料這個陣列佔用記憶體超過20M
解決方法:分批取資料,分批處理資料
問題點:一次取多少資料最合適
一次取1w條,減少資料庫IO操作次數,但php陣列就好較大
一次取1k條,增加了資料庫IO操作次數,php陣列很小
資料一共41000條
因為是迴圈查詢資料,只能返回空,所以會有一次無效的IO查詢
每次請求次數 | 響應時間 | 陣列庫IO次數 |
---|---|---|
5000 | 11.34 | 10 |
1000 | 8.02 | 6 |
2000 | 7.07 | 4 |
3000 | 5.12 | 3 |
4000 | 4.93 | 3 |
綜合考慮,覺得使用每次請求1w條資料
程式碼簡單記錄下
$filename = '測試'; $head = array('申請時間', '省', '市', '超市品牌'); $field = array('created_time', 'pro_name', 'city_name', 'brand_name'); $csv = ExportCsvService::getInstance(implode(",", $head), $field, $filename); $param['limit'] = C('SQL_LIMIT'); $i = 0; while (true) { $param['current'] = $i + 1; $info = $rainbowservice->get_list($param)['data']['list']; if (empty($info)) { $csv->end(); break; } else { $csv->sendDate($info); } unset($info); $i++; }
csv操作類
class ExportCsvService { private $content; private $filename; private $field; private static $instance; private function __construct($head,$field,$filename) { $this->field = $field; $this->filename = $filename; $this->content = iconv('UTF-8', 'GBK',$head) . PHP_EOL; } /** * 例項化服務類 * @param $head * @param $field * @param $filename * @return ExportCsvService */ public static function getInstance($head,$field,$filename) { if (!self::$instance instanceof self) { self::$instance = new self($head,$field,$filename); } return self::$instance; } /** * 拼接要匯出的資料 * @param $data */ public function sendDate($data) { foreach ($data as $key => $value) { $temp = []; foreach ($this->field as $k) { $temp[] = iconv('UTF-8', 'GBK', $value[$k]); } $this->content .= implode(",", $temp) . PHP_EOL; //用英文逗號分開 unset($temp); } } /** * 輸出資料 */ public function end() { header("Content-type:text/csv;charset=GBK"); header("Content-Disposition:attachment;filename=" . $this->filename); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); echo $this->content; } }