New in PHP 5 is a function called file_put_contents( );. It’s three things all in one: fopen, fwrite, and fclose. Want to add a line to a file? Now that’s possible with just one function call – file_put_contents( );
Of course being a more comprehensive function, one would assume that file_put_contents( ) is slower than any one of the other functions that it encompasses. But how much slower?
I ran a fairly unscientific benchmark to delve a little deeper into this issue. I have a script that generates an xml sitemap of about 1800 links. The current version first uses fopen( ) once, then uses fwrite( ) to append and then uses fclose( ) to close it at the end. What would happen if I replaced that with file_put_contents( ) every time I wanted to append to the xml file? Well I setup two scripts that do the identical thing. One uses fopen/fwrite/close and the other uses file_put_contents( ). Here are the results:
| Run # | file_put_contents( ) (secs) | fopen/fwrite/fclose (secs) |
|---|---|---|
| 1 | 2.6208 | 2.468 |
| 2 | 2.5520 | 2.5322 |
| 3 | 2.7706 | 2.5413 |
| 4 | 3.2533 | 2.5672 |
| 5 | 2.6072 | 2.5034 |
| 6 | 2.5591 | 2.4922 |
| AVG: | 2.6662 | 2.4857 |
So the fopen/fwrite/fclose version is about 7.3% faster. The speed increase makes sense. The majority of the script is a simple append of a URL to the xml file. During that operation, file_put_content( ) still has to do the functionality of fopen/fwrite/flcose every single time it adds a URL. Whereas the original script only has to do fwrite( ) when it adds URL’s.
gf4e said
Isn’t 2.4857 less than 2.6662?
George Gonzalez said
Yes, you’re right! Typo by me though – got the headers reversed. Thanks!