Minimize memory usage when dealing with large files

suggest change

Parsing a large file, such as a CSV of more than 10 MB with millions of rows, by calling file or file_get_contents can hit memory_limit:

Allowed memory size of XXXXX bytes exhausted

error. Consider the following source (top-1m.csv has exactly 1 million rows and is about 22 Mbytes of size)

var_dump(memory_get_usage(true));
$arr = file('top-1m.csv');
var_dump(memory_get_usage(true));

This outputs:

int(262144)
int(210501632)

because the interpreter needed to hold all the rows in $arr array, so it consumed ~200 Mbytes of RAM. Note that we haven’t even done anything with the contents of the array.

Now consider the following code:

var_dump(memory_get_usage(true));
$index = 1;
if (($handle = fopen("top-1m.csv", "r")) !== FALSE) {
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
        file_put_contents('top-1m-reversed.csv',$index . ',' . strrev($row[1]) . PHP_EOL, FILE_APPEND);
        $index++;
    }
    fclose($handle);
}
var_dump(memory_get_usage(true));

which outputs

int(262144)
int(262144)

memory_get_usage(true) reports allocated blocks, so the two numbers can match even when a little memory moved inside the block. fgetcsv still keeps only the current row in $row. The length argument of 1000 splits a longer line. file_put_contents with FILE_APPEND opens the output file on every row.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents