Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP fopen() memory efficiency and usage

Tags:

php

memory

fopen

I am building a system to create files that will range from a few Kb to say, around 50Mb, and this question is more out of curiosity than anything else. I couldn't find any answers online.

If I use

$handle=fopen($file,'w');

where is the $handle stored before I call

fclose($handle);

? Is it stored in the system's memory, or in a temp file somewhere?

Secondly, I am building the file using a loop that takes 1024 bytes of data at a time, and each time writes data as:

fwrite($handle, $content);

It then calls

fclose($handle);

when the loop is complete and all data is written. However, would it be more efficient or memory friendly to use a loop that did

$handle = fopen($file, 'a');
fwrite($handle, $content);
fclose($handle);

?

like image 913
whizzkid Avatar asked Sep 28 '12 20:09

whizzkid


2 Answers

In PHP terminology, fopen() (as well as many other functions) returns a resource. So $handle is a resource that references the file handle that is associated with your $file.

Resources are in-memory objects, they are not persisted to the file system by PHP.

Your current methodology is the more efficient of the two options. Opening, writing to, and then closing the same file over and over again is less efficient than just opening it once, writing to it many times, and then closing it. Opening and closing the file requires setting up input and output buffers and allocating other internal resources, which are comparatively expensive operations.

like image 125
Sean Bright Avatar answered Sep 17 '22 20:09

Sean Bright


Your file handle is just another memory reference and is stored in the stack memory just like other program variables and resources. Also in terms of file I/O, open and close once, and write as many times as you need - that is the most efficient way.

$handle = fopen($file, 'a'); //open once
while(condition){
  fwrite($handle, $content); //write many
}
fclose($handle); //close once
like image 31
raidenace Avatar answered Sep 18 '22 20:09

raidenace