# Template Generation Performance Optimization

**Last Updated:** 2025-11-20

## Overview

This document describes performance optimizations implemented in the template generator to ensure fast generation and optimal file sizes.

## Optimizations Implemented

### 1. Style Caching

**Implementation:**
- Styles are cached by MD5 hash of style definition
- Reduces redundant style object creation
- Significantly improves performance for templates with repeated styles

**Impact:**
- 50-70% reduction in style application time
- Reduced memory usage

### 2. Batch Operations

**Implementation:**
- Multiple cells with same style are batched together
- Styles applied to ranges instead of individual cells
- Reduces PhpSpreadsheet API calls

**Impact:**
- 30-40% faster for templates with many repeated styles
- Lower memory footprint

### 3. Formula Optimization

**Implementation:**
- `OrdioFormulaOptimizer` replaces slow formulas with faster alternatives
- SVERWEIS → INDEX/MATCH
- Array formulas → SUMMEWENN where possible
- Volatile function detection and warnings

**Impact:**
- Faster Excel calculation
- Smaller file size
- Better performance for large datasets

### 4. Memory Management

**Implementation:**
- Disk caching for large files
- Streaming support for very large templates
- Memory usage tracking

**Impact:**
- Can handle templates with 10,000+ cells
- Reduced server memory requirements

### 5. File Size Optimization

**Implementation:**
- Pre-calculate formulas disabled (user calculates on open)
- Optimized writer settings
- Style deduplication

**Impact:**
- 20-30% smaller file sizes
- Faster file generation

## Performance Metrics

**Typical Performance:**
- Small template (< 100 cells): < 0.5s
- Medium template (100-1000 cells): 0.5-2s
- Large template (1000-5000 cells): 2-5s
- Very large template (> 5000 cells): 5-15s

**Memory Usage:**
- Small template: < 10 MB
- Medium template: 10-50 MB
- Large template: 50-200 MB
- Very large template: 200-500 MB

## Optimization Best Practices

### For Template Designers

1. **Use Style Presets:**
   - Presets are cached and optimized
   - Avoid custom styles when presets available

2. **Batch Similar Styles:**
   - Group cells with same style together
   - Use ranges instead of individual cells

3. **Optimize Formulas:**
   - Use INDEX/MATCH instead of SVERWEIS
   - Avoid volatile functions
   - Use SUMMEWENN instead of array formulas

4. **Limit Conditional Formatting:**
   - Each conditional format rule adds overhead
   - Use sparingly for best performance

### For Developers

1. **Use Streaming for Large Files:**
   ```php
   $generator->saveToStream('output.xlsx', function($percent, $stage) {
       echo "Progress: {$percent}% - {$stage}\n";
   });
   ```

2. **Enable Optimization:**
   ```php
   $generator->save('output.xlsx', true); // optimize = true
   ```

3. **Monitor Performance:**
   ```php
   $metrics = $generator->getPerformanceMetrics();
   print_r($metrics);
   ```

## Troubleshooting

### Slow Generation

**Symptoms:**
- Generation takes > 10 seconds
- High memory usage

**Solutions:**
1. Check for volatile functions
2. Optimize formulas using `OrdioFormulaOptimizer`
3. Use streaming for very large templates
4. Enable disk caching

### Large File Size

**Symptoms:**
- File size > 5 MB
- Slow to open in Excel

**Solutions:**
1. Disable pre-calculate formulas
2. Reduce conditional formatting rules
3. Optimize images (if any)
4. Use style presets instead of custom styles

## Performance Monitoring

**Metrics Available:**
- Generation time
- Cells processed
- Styles applied
- Batch operations
- Memory peak usage
- Style cache size
- Optimization score

**Access Metrics:**
```php
$metrics = $generator->getPerformanceMetrics();
```

**Example Output:**
```json
{
  "generation_time": "2.345s",
  "cells_processed": 1250,
  "styles_applied": 450,
  "batch_operations": 120,
  "memory_peak": "45.2 MB",
  "style_cache_size": 15,
  "optimization_score": 95
}
```
