I was recently reviewing some code when a simple question came up…
What’s the fastest way to output a segmented string?
1 2 3 4 5 | echo '<div>'; echo '<span>'; echo 'This is a random number: ' . mt_rand(1,100); echo '</span>'; echo '</div>'; |
– OR –
1 2 3 4 5 6 7 | $html = ''; $html .= '<div>'; $html .= '<span>'; $html .= 'This is a random number: ' . mt_rand(1,100); $html .= '</span>'; $html .= '</div>'; echo $html; |
My initial guess was that calling echo as little as possible during a request would end up performing better as there would be no need to interact with an output buffer or perform other logic tied to STDOUT.
I ended up asking a few friends and colleges what they thought about the question and most responded with “hu?” After telling them that I was in fact serious the majority of their opinions fell on echo being the winner. Still, others thought of ways to get a segmented string out faster, like pushing them onto an array and executing echo implode(”, $array);
This difference of opinion got me thinking about what was truly the most efficient way to output a collection of strings? Curiosity got the best of me and I quickly setup some profiling tests using my Bench Class to find out the answer.
Profiling Setup
I used the following code in order to get enough data points for a solid performance comparison.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $samples = 40; $sets = array(10,20,50,100,500,1000,1500,2000,2500,3000); $results = array(); foreach($sets as $iterations) { $results[$iterations] = array(); for($i=0; $i<$samples; $i++) { Bench::start(); for($j=0;$j<$iterations;$j++) { // ... Output Test ... } $results[$iterations][] = Bench::stop(); Bench::reset(); } } |
Tests
I tested the performance on four different methods of outputting data…
- July 15, 2011
- Categories: Research
