| PHP & Web Development :: PHP
Performance + Benchmarking :: Remote File Access |
PHP remote file access: fopen() and file_get_contents()
Opening
files in PHP is easier now because of the file_get_contents() function
which is the recommended way to dump a file's contents into a string
according to the official PHP documentation. But does this PHP function
really perform better than fopen? The following test environment compares
the performance of file_get_contents to fopen when retrieving a public
Yahoo RSS feed.
Test Environment: Linux, Apache, PHP 4.3.11 with
PHP loaded using FastCGI. Zend Optimizer 2.5.7 installed. What's
Zend Optimizer?
Test Setup: Code constructs listed below.
Refresh the page to execute a new trial!
| Comparisons |
fopen(), fread()
|
- Execution time: 197.24
ms
- Average: 204.46
ms over 9055 trials
|
file_get_contents()
|
- Execution time: 130.66
ms
- Average: 201.76
ms over 9072 trials
|
| Results |
| Test |
Avg Execution Time |
Comparative Graph - (longer is slower, 100% is the fastest time)
|
| fopen(), fread() |
204.46 ms |
101% |
| file_get_contents() |
201.76 ms |
100% |
Discussion: Surprisingly, there is not much difference!
I am writing this at 125 trials of the above test, and it looks like
fopen() is actually a little faster than file_get_contents(). I checked
this again by reversing which test was performed first, and still
received the same results. Even testing this script on another URL,
the results were the same. So why use file_get_contents()? Well, it
is certainly clearer in code structure and because it combines the
file open and file read into the same function, you only need to do
error handling once. Some situations require the use of fopen(), especially
if any writing to the file is required. The sister function to file_get_contents(),
file_put_contents(), was not available until PHP 5.0, which is not
used yet by many hosting companies.
Another set of PHP functionality, the CURL functions, are also very
useful and have proven to be much faster than either of the above
functions. The problem is that CURL is not compiled with PHP by default,
so many users cannot use CURL in a pre-compiled, hosted environment.
I have written an object oriented remote
file access script using both file_get_contents() and fopen(),
depending on which version of PHP is installed on the server. See
this script for more information on the usage of fopen() and file_get_contents().
|