← Documentation

Zandy_Template Performance Optimization Guide

This document provides performance optimization tips and best practices for the Zandy_Template template engine.

Table of Contents

  1. Performance Characteristics
  2. Caching Mechanism
  3. Compile Optimization
  4. Runtime Optimization
  5. Memory Optimization
  6. Performance Testing

Performance Characteristics

Zandy_Template is a compiled template engine with the following performance characteristics:

Performance comparison:


Caching Mechanism

How Caching Works

  1. First compile: template file → parse → PHP code → cache file
  2. Subsequent use: check the template file modification time → use the cache (if unmodified)
  3. Force refresh: set $forceRefreshCache = true to 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:

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 time

3. 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


Summary

  1. Make full use of the cache: avoid recompilation, 90%+ performance gain
  2. Split large templates: split large templates into several small templates to improve compile speed
  3. Optimize variable passing: pass only the variables that are needed to reduce memory usage
  4. Loop optimization: avoid complex computation inside loops
  5. Clean the cache periodically: keep the cache directory tidy and improve I/O performance

For more details, please refer to: