PHP NOTES: Benchmarking heredoc notation[Shaun's PHP Scripts > Notes > Benchmarking heredoc notation] This note describes benchmarks of multiple echo statements against single heredoc statements. Starting with version 4, PHP provides "heredoc" notation, which is a method of printing or echoing large amounts of text at once. Heredoc notation can save tons of keystrokes, and lets you avoid the hassle of escaping certain characters. It's simple to use:
But I've often wondered: is heredoc notation faster than using multiple echo statements? Many people, myself included, write their scripts with readability in mind. For me, that means I try to keep each line of a script within the standard 80-column viewable real estate of a unix text editor. In my older scripts this resulted in a lot of extra calls to "echo" to prevent long lines from running off into the margin. If I wanted to print out a 120-character blob of text, I'd break it into two smaller echo statements so that the script was still easy to read at the terminal. Somewhere along the line, it hit me that perhaps this wasn't such a good idea; and that all those extra echo statements might be hindering the performance of my scripts. I decided to test my hunch by doing a couple of simple benchmarks. First, I created bench1.php, which uses heredoc notation to echo a line of text with a few variables. In order to generate a measurable execution time, the line of text is echoed 10,000 times:
Then I created bench2.php, which did the exact same thing but used two echo statements instead of heredoc notation:
With the help of the time command, I found that the heredoc notation was indeed slightly faster than using two echo statements. I only ran the test twice, but was satisfied that the results were consistent:
Both times, the heredoc version of the script took about 8 seconds to finish, while the script with two echo statements ran for about 11 seconds. Convinced that I was onto something, I decided to create a more accurate test environment. I replaced bench1.php and bench2.php with new scripts which echoed out a short HTML page. As is frequently done in real-world scripting, certain attributes of the HTML - such as the background color, text color, and font face - were stored in variables.
When the benchmark was run on the new scripts, heredoc notation clearly won again:
Of course a real benchmark would have run these tests hundreds of times apiece instead of just twice, so this data is hardly scientific. It's also worth noting that your average script doesn't do something 10,000 times in a row, so the benefit of CPU time gained is going to be negligible in most cases. The experiment was enough to make me a believer in heredoc notation, though; I won't be using multiple echo statements in the future. |
|
|