Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is file_get_contents slower than include?

Tags:

php

caching

xml

have a file caching system for a php 5 library i use often. when the request is made i check for a cached file, if there is one i render it and exit.

$contents = file_get_contents( self::_cacheFile() );
echo $contents;
exit();     

i have to do file_get_contents instead of just include because of cached xml files with the pesky

`<?xml version="1.0"?>` 

is there a better way to pull in my cache files without shorttags firing?

like image 949
David Morrow Avatar asked Feb 24 '10 18:02

David Morrow


1 Answers

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
like image 137
Gordon Avatar answered Oct 04 '22 06:10

Gordon