whizzkid
whizzkid

Reputation: 324

PHP fopen() memory efficiency and usage

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);

?

Upvotes: 8

Views: 8766

Answers (3)

Sean Bright
Sean Bright

Reputation: 120644

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.

Upvotes: 10

s.webbandit
s.webbandit

Reputation: 17000

  1. According to PHP DOCS fopen() creates a stream which is a File handle. It is associated with file in filesystem.

  2. Creating new File handle every time you need to write another 1024 bytes would be terribly slow.

Upvotes: 0

raidenace
raidenace

Reputation: 12826

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

Upvotes: 2

Related Questions