Monday, October 12, 2009

file_get_contents() vs fread() - Speed Test and Benchmarking

File access is commonly found in any PHP application. Be it caching, or reading data from a file or what. Lately I've been wondering, whether the use of file_get_contents() over fread() is a good practice (i always prefer file_get_contents()).

So this morning I ran a test between this 2 methods of reading a file. The script I used to run is at http://thephpcode.pastebin.com/f2e84fab1

So here's the result from the tests of 5 runs:
 fread() (seconds)file_get_contents() (seconds)
Mean0.036740.01322
Min0.0307109355926510.0098111629486084
Max0.045550823211670.016166925430298


So here it's clear that file_get_contents() is much faster than fread(), mainly because fread() consists of an overhead additional loop and several functions.

1 comment:

Sjors said...

What filesize did you have?
In a lot of cases fread is much faster.