Home > Backend Development > PHP Tutorial > PHP长时间运行的内存溢出。

PHP长时间运行的内存溢出。

WBOY
Release: 2016-06-06 20:10:49
Original
1242 people have browsed it

循环一个文件夹下的 txt 文件,将其中数据按行读取存进数据库 出现 Fatal error: Allowed memory size of 134217728 bytes exhausted 的错误提示,

代码如下,我每一个 txt 文件都不大(100k左右),而且是按行进行读取的,原因在哪呢?

<code>        $file = new \FilesystemIterator($fileName);
        foreach ($file as $fileinfo) {

            if ( $fileinfo->isFile() ) {
                $fp = fopen($fileName . '/' . $fileinfo->getFilename(), 'r');
                while(! feof($fp)) {
                    $data['score'] = 7;
                    $data['code'] = fgets($fp);
                    $this->book->add($data);//存进数据库
                }

                fclose($fp);
            }

        }</code>
Copy after login
Copy after login

回复内容:

循环一个文件夹下的 txt 文件,将其中数据按行读取存进数据库 出现 Fatal error: Allowed memory size of 134217728 bytes exhausted 的错误提示,

代码如下,我每一个 txt 文件都不大(100k左右),而且是按行进行读取的,原因在哪呢?

<code>        $file = new \FilesystemIterator($fileName);
        foreach ($file as $fileinfo) {

            if ( $fileinfo->isFile() ) {
                $fp = fopen($fileName . '/' . $fileinfo->getFilename(), 'r');
                while(! feof($fp)) {
                    $data['score'] = 7;
                    $data['code'] = fgets($fp);
                    $this->book->add($data);//存进数据库
                }

                fclose($fp);
            }

        }</code>
Copy after login
Copy after login

用关键字yield 进行迭代操作,不会储存中间变量节省内存,要求php5.5+

$this->book->add($data);
unset($data);

while循环时$data会发生写时复制(COW),这些内存只有在你的脚本执行结束后才会释放

安装xdebug或者xhprof查看性能分析报告。

我估计是框架的配置,sql做了收集

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template