Efficiency and memory usage of PHP fopen ()

I am creating a system for creating files of a few kilobytes in size to say about 50 MB, and this question is more out of curiosity than anything else. I could not find the answers on the Internet.

If i use

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

where is the $ handle stored before I call

 fclose($handle); 

? Is it stored in system memory or in a temporary file somewhere?

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

 fwrite($handle, $content); 

Then he calls

 fclose($handle); 

when the cycle is completed and all data is written. However, it would be more efficient or wise to use memory in a loop that executed

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

?

+4
source share
3 answers

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

Resources are objects in memory; they are not stored in the PHP file system.

Your current methodology is the more effective of the two options. Opening, writing, and then closing the same file over and over is less effective than simply opening it once, writing it repeatedly, and then closing it. Opening and closing a file requires tuning input and output buffers and allocating other internal resources, which are relatively expensive operations. This is a bad analogy, but it would be like turning your car engine off every time you come to a stop sign.

+4
source

Your file descriptor is another reference to memory and is stored in the stack memory in the same way as other program variables and resources. Also, in terms of file I / O, open and close once and record as many times as you need - this is the most efficient way.

 $handle = fopen($file, 'a'); //open once while(condition){ fwrite($handle, $content); //write many } fclose($handle); //close once 
+1
source
  • According to PHP DOCS fopen () creates a stream, which is a File handle . It is associated with a file in the file system.

  • Creating a new File handle every time you need to write another 1024 bytes will be very slow.

0
source

Source: https://habr.com/ru/post/1436892/


All Articles