# Framework Performance

> Performance optimization features and monitoring built into the PHP framework.

## 🔧 Built-in Performance Features

### Connection Pooling

The framework includes advanced database connection pooling with health monitoring:

```php
// Automatic connection pooling
$pool = new ConnectionPool([
    'min_connections' => 5,
    'max_connections' => 20,
    'idle_timeout' => 300,
    'health_check_interval' => 60
]);

// Health monitoring
$healthChecker = new ConnectionHealthChecker($pool);
$healthStatus = $healthChecker->checkHealth();
```

### Query Optimization

#### N+1 Query Prevention
The framework automatically detects and eliminates N+1 queries:

```php
// Automatic eager loading detection
$users = $userRepository->findWithRelations(['posts', 'comments']);

// Batch loading for performance
$posts = $postRepository->loadBatch($userIds);
```

#### Query Caching
Built-in query result caching with intelligent invalidation:

```php
// Cache configuration
$cacheConfig = [
    'default_ttl' => 3600,
    'strategy' => 'write-through',
    'invalidation' => 'tag-based'
];

// Automatic query caching
$result = $repository->findCached('user-posts-' . $userId);
```

### View System Performance

#### Template Compilation
PHP templates are compiled and cached for optimal performance:

```php
// Template compilation
$viewProcessor = new ViewProcessor([
    'cache_path' => '/var/cache/views',
    'auto_reload' => false, // Production setting
    'optimize' => true
]);
```

#### Fragment Caching
Cache expensive template fragments:

```html
<!-- Fragment caching in templates -->
<cache key="user-stats-<?= $userId ?>" ttl="3600">
    <?php foreach($stats as $stat): ?>
        <div class="stat"><?= $stat->render() ?></div>
    <?php endforeach; ?>
</cache>
```

## 📊 Performance Monitoring

### Analytics Integration

The framework includes comprehensive performance analytics:

```php
// Performance monitoring
class PerformanceMiddleware implements HttpMiddleware 
{
    public function handle(Request $request, Next $next): Response 
    {
        $startTime = microtime(true);
        $startMemory = memory_get_usage();
        
        $response = $next($request);
        
        $this->recordMetrics([
            'duration' => microtime(true) - $startTime,
            'memory' => memory_get_usage() - $startMemory,
            'route' => $request->getRoute(),
            'status' => $response->getStatusCode()
        ]);
        
        return $response;
    }
}
```

### Database Performance Tracking

Monitor database query performance automatically:

```php
// Query performance logging
class QueryLogger implements QueryMiddleware
{
    public function beforeQuery(string $sql, array $params): void
    {
        $this->startTime = microtime(true);
    }
    
    public function afterQuery(string $sql, array $params): void
    {
        $duration = microtime(true) - $this->startTime;
        
        if ($duration > 0.1) { // Log slow queries
            $this->logger->warning('Slow query detected', [
                'sql' => $sql,
                'duration' => $duration,
                'params' => $params
            ]);
        }
    }
}
```

## 🚀 Optimization Strategies

### HTTP Layer Optimizations

#### Response Compression
Automatic response compression based on content type:

```php
// Compression middleware
class CompressionMiddleware implements HttpMiddleware
{
    public function handle(Request $request, Next $next): Response
    {
        $response = $next($request);
        
        if ($this->shouldCompress($response)) {
            return $this->compress($response);
        }
        
        return $response;
    }
}
```

#### HTTP Caching
Intelligent HTTP caching with ETag support:

```php
// Cache headers
$response->headers->set('Cache-Control', 'public, max-age=3600');
$response->headers->set('ETag', hash('sha256', $content));

// Conditional requests
if ($request->headers->get('If-None-Match') === $etag) {
    return new Response('', 304);
}
```

### Asset Optimization

#### Static File Serving
Optimized static file serving with proper headers:

```nginx
# Nginx configuration for static assets
location /assets/ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    add_header Vary "Accept-Encoding";
    
    gzip_static on;
    brotli_static on;
}
```

#### Asset Bundling
Framework integration with Vite for optimal asset bundling:

```php
// Asset helper
class AssetHelper
{
    public function getAssetUrl(string $asset): string
    {
        $manifest = $this->loadManifest();
        return $manifest[$asset]['url'] ?? $asset;
    }
    
    public function getCriticalCss(): string
    {
        return $this->inlineAsset('critical.css');
    }
}
```

## 🔍 Performance Profiling

### Built-in Profiler

Enable the framework profiler for detailed performance analysis:

```php
// Profiler configuration
$profiler = new FrameworkProfiler([
    'enabled' => $this->isDebugMode(),
    'storage' => 'file', // or 'redis'
    'threshold' => 100, // ms
    'collect' => [
        'queries',
        'views',
        'cache',
        'events'
    ]
]);
```

### Memory Usage Tracking

Monitor memory usage throughout the request lifecycle:

```php
// Memory tracking
class MemoryTracker
{
    public function trackOperation(string $operation, callable $callback)
    {
        $beforeMemory = memory_get_usage(true);
        $beforePeak = memory_get_peak_usage(true);
        
        $result = $callback();
        
        $afterMemory = memory_get_usage(true);
        $afterPeak = memory_get_peak_usage(true);
        
        $this->recordMemoryUsage([
            'operation' => $operation,
            'memory_used' => $afterMemory - $beforeMemory,
            'peak_increase' => $afterPeak - $beforePeak
        ]);
        
        return $result;
    }
}
```

## ⚡ Performance Best Practices

### Database Best Practices

1. **Use Indexes**: Ensure proper database indexing
2. **Lazy Loading**: Load data only when needed
3. **Batch Operations**: Group database operations
4. **Connection Reuse**: Leverage connection pooling

```php
// Efficient database operations
class UserService
{
    public function getUsersWithPosts(array $userIds): array
    {
        // Single query with join instead of N+1
        return $this->repository->findUsersWithPosts($userIds);
    }
    
    public function batchUpdateUsers(array $updates): void
    {
        // Batch update instead of individual queries
        $this->repository->batchUpdate($updates);
    }
}
```

### View Optimization

1. **Template Caching**: Cache compiled templates
2. **Fragment Caching**: Cache expensive view fragments
3. **Lazy Loading**: Load view components on demand
4. **Asset Optimization**: Minify and compress assets

```php
// Optimized view rendering
class OptimizedViewController
{
    public function render(string $template, array $data): Response
    {
        // Use cached template if available
        $compiled = $this->templateCache->get($template);
        
        if (!$compiled) {  
            $compiled = $this->compiler->compile($template);
            $this->templateCache->set($template, $compiled);
        }
        
        return $this->renderCompiled($compiled, $data);
    }
}
```

## 📈 Monitoring & Alerts

### Performance Metrics Collection

Collect and analyze key performance metrics:

```php
// Metrics collection
$metrics = [
    'response_time' => $responseTime,
    'memory_usage' => memory_get_peak_usage(true),
    'database_queries' => $queryCount,
    'cache_hits' => $cacheHits,
    'cache_misses' => $cacheMisses
];

$this->metricsCollector->record($metrics);
```

### Alert Configuration

Set up alerts for performance degradation:

```php
// Performance alerts
$alertConfig = [
    'response_time_threshold' => 1000, // ms
    'memory_threshold' => 128 * 1024 * 1024, // 128MB
    'query_count_threshold' => 50,
    'error_rate_threshold' => 0.01 // 1%
];
```

---

*For general performance guidelines, see [Performance Guidelines](../../development/performance.md)*  
*For analytics configuration, see [Analytics System](../analytics/README.md)*