A few days ago, i’ve been working on a templating system.
If you’re not used to what a template is, let’s say it’s just a chunk of HTML you use in multiple places, and that it can be filled with variables. That, for example, could be a template:
<div class="user"> <h3><?php echo $name; ?></h3> <img src="<?php echo $picture; ?>"/> </div>
We want to fill that template with proper variables, then return the generated string.
There are two ways of doing that:
- using a variable to store every line of our template (see case 1)
- using the output buffering (see case 2)
Case 1:
<?php // template.php -- the template $template .= '<div class="user">'; $template .= '<h3>'. $name .'</h3>'; $template .= '<img src="'. $picture .'"/>'; $template .= '</div>'; // script.php -- function to get the template function get_template($name, $picture){ $template = ''; include('template.php'); return $template; } ?>
Case 2:
<?php // template.php -- the template ?> <div class="user"> <h3><?php echo $name; ?></h3> <img src="<?php echo $picture; ?>"/> </div> <?php // script.php -- function to get the template function get_template($name, $picture){ ob_start(); include('template.php'); return ob_get_clean(); } ?>
I believe everybody agrees that case 2 is the easiest to use. You just do like you always do, simply write HTML, and the output is stored into a buffer instead of being sent directly.
But then i told myself « that’s great, but what happens when the buffer needs to store a lot of data, that must slow things down, right? ».
Well, i did some benchmarking to answer that question, and here are the results:
Using output buffering:
- small amount of data: 1.5E-6
- big amount of data: 4.8E-5
Using a variable:
- small amount of data: 7.9E-7
- big amount of data: 1.3E-5
These values represent the average execution time of the script, in seconds.
What i mean by small amount of data is 300 unicode characters, and 30,000 for big amount of data.
You’ll notice the difference between the results: using output buffering takes about twice longer than using a variable.
But we’re talking microseconds here: output buffering takes 0.7 more microseconds, up to 35 more microseconds with a lot of data.
Enough said, compared to the ease of use output buffering gives us, it’s really fair to use it here. Output buffering wins!