Often times in PHP you find yourself needing to insert text. Most sites do this by using a database backend, but you also have the option to include data from a text file. Three methods are available for this; require, include, and file_get_contents. Which is fastest, which is best? When should you use one over the other?
To start, let’s look at the difference between include and require, as they are often used interchangeably. According to the PHP web site, both functions are identical except for how they handle errors. When an error occurs; include produces a warning while require produces a fatal error. There are also include_once and require_once which will not be tested here, but may make it into another benchmark. Because these two are so often used interchangeably and reportedly function in the same way, I would expect the speeds to be really close.
There is a third method that I plan to test; that is get_file_contents. According to the PHP site, this is a quick way of including text.
Each test will be run 10 times with 1,000 iterations in each test. The data included will be ‘The quick brown fox jumped over the lazy dog.’
The difference in results was statistically insignificant. All tests hovered around a quarter of a second for 1,000 iterations. I would imagine the similarity is due to the internal methods of these functions. They probably function in much the same way.
So, which to use? As expected, include and require were the same speed. So, pick between these two based on how you want errors reported. Require throws a fatal error while include throws a notice. get_file_contents is not really intended to output text. It is intended to open a file and fill a variable with the text in that file. So, if that is your need, use it.