What is the best option? (Performance on frequent requests permlink)
- Multiple access on data files (Several access to filesystem is a problem?):
readfile("meta-data.html");
readfile("header.html");
readfile("ads.html");
readfile("body-tags.html");
readfile("ads2.html");
readfile("profile-target-userA.html");
...
- Preprocess parts of the page with template and str_replace:
$file = file_get_contents("template.code");
$file = str_replace("<!-- meta-data -->", $new_meta_data, $file);
$file = str_replace("<!-- header-->", $new_header, $file);
...
echo $file;
Other alternative methods are welcome.
Assuming that your OS has an I/O cache, the second approach may very well wind up being slower. Moving strings around in memory (which is what
str_replaceis going to do) can be considerably more expensive than hitting the disk, especially when the files are currently cached by the OS.However, you should be basing your template/view system on maintainability and flexibility, not just performance. It’s better to sacrifice a bit in terms of performance to produce more maintainable templates.
Usually, I see templates written as PHP files — one would set a few variables and then
include()the templates. PHP will then execute them, which gives you quite a bit of flexibility in coding your views. And, if a template file really is just HTML,include()will have the same effect asreadfile().