Is there any performance difference between writing a file as an answer and writing to a buffered file?

14

I have a t2.micro instance in amazon where I use IIS 10 as a server and webforms in the application (C #).

In a certain part of the application, I need to get a list of image files from a particular folder, zip it and reply as a download to the user.

The problem is that in a specific case, when the ZIP file has reached 1GB, the server simply hangs when the user clicks the button to download this ZIP file.

I'd like to get some questions, not about the above problem, but a technical question as to how the download responses work, when you write it through a Stream or something like that.

For the server, is there any difference between writing a response from a file directly and writing using buffer (using while , for example)?

Example 1 - Directly:

// headers para download
readfile($filename);

Example 2 - Per Buffer:

// headers para download

$handler = fopen($filename);

while(feof($handler) !== false) {
   echo fgets($handler, 4096);
}
    
asked by anonymous 16.03.2018 / 14:08

1 answer

11

There are differences, yes.

In the first case the file will be loaded entirely into the server's memory before being sent to the client.

In the second case, the file will be partially loaded into memory and sent back to the client. This way you compromise the memory of the server less, because it can serve multiple requests consuming little memory for each of them.

About your problem, you are probably using the first case (loading the entire file into memory), causing the t2.micro server (which curiously has 1 GB of RAM ) crash and stop responding.

In terms of performance, using the technique of the second case, the download will not only save memory but will also begin to be made available to the user earlier, since the time to load part of a vs an entire file in the server's memory are quite different.

There is a partial implementation made in Java with Spring in which you can also reproduce this behavior, also showing the two situations.

    
16.03.2018 / 14:36