Home » Php » What's faster? file_put_contents(); fopen(); fwrite(); fclose();? [closed]

What's faster? file_put_contents(); fopen(); fwrite(); fclose();? [closed]

Posted by: admin November 30, 2017 Leave a comment

Questions:

What is better? I have my own MySQL log so it has about 90MB, but I’m not sure which one should I use. It opens file EVERYTIME there is query to execute.

What’s faster?

Answers:

According to this article, the fwrite() is a smidgen faster. (Link to Wayback Machine, because site no longer exists.)

My guess is that file_put_contents() is just a wrapper around those three methods anyways, so you would lose the overhead.

EDIT : This site has the same information.

Questions:
Answers:

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

Check the docs:
http://php.net/manual/en/function.file-put-contents.php

Shaun

Questions:
Answers:

Depends on your use-case. I’ve opened files which were over .5 GB, and I certainly didn’t want to use file() or file_get_contents(); And file_put_contents couldn’t work because I needed to read the file too.

If you’re really just interested in appending a file without reading, it doesn’t terribly matter; if you’re trying to read a whole file into memory (or write a whole file from memory), it similarly does not really matter — the speed gain, as near as I’ve seen, is round-off error.

BUT, if you’re expecting that these files will ever grow to gargantuan beasts, or if you only need a small subset of the number of lines of a given file, I cannot suggest use of fopen (or the SplFileObject, which is AWESOME) strongly enough — it is really easy to read from the middle of a file with these.


Since you’re just logging, on the other hand, I, personally, find it clearer and more concise to simply use file_put_contents with the append flag. It lets everyone know what’s going on without having to look twice.

Questions:
Answers:

As per usual, have you benchmarked it? file_put_contents is essentially just a wrapper around the 3 f*() calls anyways, so at most you’re losing out by doing one extra function call, but gaining somewhat by having less front-end code to parse.

Questions:
Answers:
  1. If there is only one write-operation for one file in a request, file_put_contents is better than fwrite, because it has wrappered open, write and close functions, and as fast as fwrite.
  2. If there are multi-write for one file in a request, we need open file first, then write multi-times, so fwrite is faster. But, if it is a very busy system, which has a lot of “open files”(ulimit -a | grep “open files”), file_put_contents will be a more reasonable choose, because it keep the file handler shorter than fwrite.