Zandy_Template Performance Optimization Guide
This document provides performance optimization tips and best practices for the Zandy_Template template engine.
Table of Contents
- Performance Characteristics
- Caching Mechanism
- Compile Optimization
- Runtime Optimization
- Memory Optimization
- Performance Testing
Performance Characteristics
Zandy_Template is a compiled template engine with the following performance characteristics:
- ✅ Compile-time parsing: templates are compiled into PHP code on first use and executed directly as PHP afterwards
- ✅ Zero runtime overhead: the compiled code is pure PHP, with performance close to native PHP
- ✅ Smart caching: template file changes are detected automatically, and recompilation happens only when necessary
- ✅ Efficient string handling: heredoc syntax is used, giving excellent string processing performance
Performance comparison:
- Compiled template engines (Zandy_Template): performance close to native PHP
- Interpreted template engines: parsed at runtime, lower performance
Caching Mechanism
How Caching Works
- First compile: template file → parse → PHP code → cache file
- Subsequent use: check the template file modification time → use the cache (if unmodified)
- Force refresh: set
$forceRefreshCache = trueto force recompilation
Cache Usage Recommendations
// ✅ Recommended: make full use of the cache
// First compile (slower, about 30-50ms)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
// Subsequent use (very fast, about 0.5-2ms, 90%+ performance gain)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
// Force a refresh after the template changes (development environment)
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, true);Cache Directory Optimization
// ✅ Recommended: use a dedicated cache directory
$cacheDir = '/path/to/cache/';
// Suggestions:
// 1. Use SSD storage (improves I/O performance)
// 2. Clean up old cache periodically (recommended at deployment time)
// 3. Set appropriate file permissions (avoid permission problems)
// Example of cleaning old cache
function cleanOldCache($cacheDir, $maxAge = 3600) {
$files = glob($cacheDir . '**/*.php');
foreach ($files as $file) {
if (time() - filemtime($file) > $maxAge) {
unlink($file);
}
}
}Compile Optimization
0. Deployment-time Precompile (v1.11.0, standard for production releases)
scripts/precompile.php recursively precompiles all templates at deployment time—zero compile latency on the first request:
php scripts/precompile.php <template directory> <cache directory>
# Outputs per-file results + a summary; exit code 1 if any fails (can gate a release pipeline)The recursive scan includes subdirectories, and relative paths serve as template names; plugin syntax such as inheritance/macro/fragment cache is automatically available (plugins/builtin.php is loaded internally). Already-fresh cache entries are skipped automatically (incremental warm-up).
0.1 Concurrent Compile Lock (built in)
Concurrent compiles of the same cache file are serialized through a lock file—when many requests hit an uncompiled template at high concurrency, only one request performs the compile while the others wait and then reuse the artifact, avoiding duplicate compilation and write races on the artifact. No configuration needed.
1. Template File Size
// ✅ Recommended: split large templates into multiple small templates
// Large template (not recommended)
// template.htm (5000+ lines)
// Small templates (recommended)
// header.htm
// content.htm
// footer.htm
// Use template includes
<!--{template header.htm}-->
<!--{template content.htm}-->
<!--{template footer.htm}-->Reasons:
- Small templates compile faster
- Easier to maintain and reuse
- Can be cached independently
2. Reduce Regular Expression Complexity
// ✅ Recommended: use simple template syntax
{$var} // simple variable
{$array['key']} // array access
// ⚠️ Avoid: overly complex expressions
{echo complex_function_call($var1, $var2, $var3)} // complex expressions increase parsing time3. Template Comments
// ✅ Recommended: use template comments (removed at compile time, no performance impact)
<!--{* 这是注释,编译后会被移除 *}-->
// ❌ Not recommended: use HTML comments (adds to the output)
<!-- This is an HTML comment and will be output to the page -->Runtime Optimization
1. Variable Passing Optimization
// ✅ Recommended: pass only the variables that are needed
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
'user' => $user, // pass only the variables the template needs
'data' => $data
]);
// ❌ Not recommended: pass a large number of unneeded variables
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
'user' => $user,
'data' => $data,
'unused1' => $large_array, // not needed by the template, wastes memory
'unused2' => $large_object
]);2. Loop Optimization
// ✅ Recommended: avoid complex computation inside loops
<!--{loop $items as $item}-->
{$item['name']} <!-- direct access, good performance -->
<!--{/loop}-->
// ⚠️ Avoid: complex computation inside a loop
<!--{loop $items as $item}-->
{echo complex_function($item)} <!-- executed on every iteration, poor performance -->
<!--{/loop}-->
// ✅ Recommended: preprocess data outside the loop
<?php
$processed_items = array_map(function($item) {
return complex_function($item);
}, $items);
?>
<!--{loop $processed_items as $item}-->
{$item}
<!--{/loop}-->3. Conditional Optimization
// ✅ Recommended: use simple conditions
<!--{if $status == 'active'}-->
Active
<!--{/if}-->
// ⚠️ Avoid: complex conditions
<!--{if complex_function($var1, $var2) && another_function($var3)}-->
Content
<!--{/if}-->Memory Optimization
1. Large Array Handling
// ✅ Recommended: process large arrays in batches
$large_array = [/* 10000+ items */];
// Process in batches
$chunk_size = 100;
for ($i = 0; $i < count($large_array); $i += $chunk_size) {
$chunk = array_slice($large_array, $i, $chunk_size);
$html = Zandy_Template::outString('list.htm', $tplDir, $cacheDir, false, [
'items' => $chunk
]);
echo $html;
}
// ❌ Not recommended: process a large array all at once
$html = Zandy_Template::outString('list.htm', $tplDir, $cacheDir, false, [
'items' => $large_array // may cause memory exhaustion
]);2. Output Buffering Optimization
// ✅ Recommended: use output buffering to control memory
ob_start();
Zandy_Template::includeTemplate('template.htm', $tplDir, $cacheDir);
$html = ob_get_clean();
// For large templates, you can set the output buffer size
ini_set('output_buffering', '4096');Performance Testing
Benchmark Example
// Test compile performance
$start = microtime(true);
Zandy_Template::outCache('template.htm', $tplDir, $cacheDir, true);
$compile_time = (microtime(true) - $start) * 1000; // milliseconds
// Test runtime performance
$iterations = 100;
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
Zandy_Template::outString('template.htm', $tplDir, $cacheDir);
}
$runtime_time = ((microtime(true) - $start) / $iterations) * 1000; // milliseconds per run
echo "Compile time: {$compile_time}ms\n";
echo "Runtime: {$runtime_time}ms per run\n";Performance Metric Reference
- Compile time: < 50ms (medium template, < 1000 lines)
- Runtime: < 2ms per run (with cache)
- Memory usage: < 10MB (medium template)
Summary
- Make full use of the cache: avoid recompilation, 90%+ performance gain
- Split large templates: split large templates into several small templates to improve compile speed
- Optimize variable passing: pass only the variables that are needed to reduce memory usage
- Loop optimization: avoid complex computation inside loops
- Clean the cache periodically: keep the cache directory tidy and improve I/O performance
For more details, please refer to: