Is file_get_contents slower than include?
Since include
will evaluate the content of the files, e.g. run in through the PHP interpreter and also use the include_path to find files, I'd say include
is slower. file_get_contents
will just treat the contents of a file as string. Less overhead, more speed.
From the manual page:
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
However, if you are after outputting the file, instead of getting it into a string, readfile()
is even a tiny bit faster than file_get_contents
. Given that include
'ing will output any non PHP content as well, this likely more likely what you are after I guess.
Revised benchmark on my desktop machine:
$start1 = microtime(1);for($i=0; $i<100000; $i++) { include 'log.txt';}$end1 = microtime(1) - $start1;
and
$start2 = microtime(1);for($i=0; $i<100000; $i++) { echo file_get_contents('log.txt');}$end2 = microtime(1) - $start2;
and
$start3 = microtime(1);for($i=0; $i<100000; $i++) { readfile('log.txt');}$end3 = microtime(1) - $start3;
Result
echo PHP_EOL, $end1, // 137.577358961 PHP_EOL, $end2, // 136.229552984 PHP_EOL, $end3; // 136.849179029
file_get_contents
and include
doesn't do the same thing:
file_get_contents
reads the content of a file, and returns it as a stringinclude
will execute the content of the file.
About the speed, without an opcode cache, I suppose file_get_contents
should theoretically be faster, as it does less calculation (no compilation/execution of the code).
Still, what matters the most is probably what you are trying to do: if you only want to read a file, you should use file_get_contents
.