【问题标题】:Read Specific Lines From Big File Fast with Low Memory Usage以低内存使用快速从大文件中读取特定行
【发布时间】:2022-07-12 01:30:34
【问题描述】:

我从这里得到灵感从文件的特定行读取行。

但是当我测试它以从大文件中获取行范围时:我得到了 2 个不同的结果

这是从 10mb 文件中读取 100 行的基准测试结果:

Function v1 via file():  in 35ms with memory usage 12.00Mb
Function v2 via SplFileObject: in 956ms with memory usage 2.00Mb 

我的问题,有没有其他方法可以做到这一点,所以它像使用 file() 一样快,但像使用 SplFileObject 那样内存不足?

我目前的职能:

function get_line_content_range_v1($line_number_start, $line_number_end) {

        $content = array();

        $data = file('10mb.txt');
        for($i = $line_number_start; $i <= $line_number_end; $i++) {
            $content[] = $data[$i];
        }

        return $content;

}

function get_line_content_range_v2($line_number_start, $line_number_end) {

        $content = array();

        $file = new SplFileObject("10mb.txt", "r");
        for($i = $line_number_start; $i <= $line_number_end; $i++) {
            $file->seek($i);
            $content[] = $file->current();
        }

        return $content;

}

【问题讨论】:

    标签: php


    【解决方案1】:

    使用生成器来节省内存。无需将所有内容都保存在 RAM 中。

    function get_line_content_range_v3($line_number_start, $line_number_end)
    {
        $filehandle  = fopen('10mb.txt', 'r');
        $line_number = 0;
        while (++$line_number <= $line_number_end) {
            $line = fgets($filehandle);
            if ($line_number < $line_number_start) {
                continue;
            }
            yield $line;
        }
        fclose($filehandle);
    }
    
    foreach (get_line_content_range_v3(12, 15) as $line) {
        echo $line;
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      相关资源
      最近更新 更多