# Performance Budget

This document defines the performance budget for the CCL UI Components library and provides guidelines for maintaining optimal performance.

## Budget Thresholds

### Bundle Size Limits

| Metric | Threshold | Current | Status |
|--------|-----------|---------|--------|
| **Library Bundle (Raw)** | ≤ 200 KB | ~124 KB | ✅ |
| **Library Bundle (Gzipped)** | ≤ 50 KB | ~15.9 KB | ✅ |
| **Per Component (Raw)** | ≤ 10 KB | Varies | ✅ |
| **Per Component (Gzipped)** | ≤ 3 KB | Varies | ✅ |

### Performance Limits

| Metric | Threshold | Target |
|--------|-----------|--------|
| **Render Time** | ≤ 50 ms | < 30 ms |
| **First Paint** | ≤ 100 ms | < 50 ms |
| **Memory Usage** | ≤ 50 MB | < 30 MB |
| **Memory Leaks** | 0 MB | 0 MB |

### Component-Specific Budgets

| Component | Max Size | Max Gzipped | Current Status |
|-----------|----------|-------------|----------------|
| Button | 5 KB | 1.5 KB | ✅ |
| Input | 8 KB | 2 KB | ✅ |
| Modal | 12 KB | 3 KB | ✅ |
| Toast | 6 KB | 1.8 KB | ✅ |
| Loading | 4 KB | 1.2 KB | ✅ |
| Badge | 3 KB | 1 KB | ✅ |

## Performance Monitoring

### Automated Checks

The library includes automated performance monitoring through:

1. **CI/CD Pipeline**: Performance budget checks run on every PR
2. **Bundle Analysis**: Automated bundle size and composition analysis
3. **Performance Tests**: Automated render time and memory leak tests
4. **Threshold Alerts**: Warnings when budgets are exceeded

### Manual Testing

Run performance checks locally:

```bash
# Run all performance checks
npm run perf:check

# Check bundle size budget
npm run perf:budget

# Analyze bundle composition
npm run perf:analyze

# Run performance tests
npm run perf:test
```

### Performance Monitoring in Development

```typescript
import { PerformanceMonitor } from '@Crystal-Code-Labs/ccl-ui-components';

// In your component
constructor(private perfMonitor: PerformanceMonitor) {}

ngAfterViewInit() {
  const startTime = performance.now();
  // Component initialization
  const endTime = performance.now();
  
  this.perfMonitor.recordRenderTime('MyComponent', endTime - startTime);
  this.perfMonitor.recordMemoryUsage('MyComponent');
}
```

## Performance Guidelines

### Bundle Size Optimization

1. **Tree Shaking**: Use ES modules and avoid side effects
2. **Code Splitting**: Implement lazy loading for large components
3. **Dependency Management**: Avoid large dependencies, prefer lightweight alternatives
4. **Dead Code Elimination**: Remove unused code and imports

### Render Performance

1. **OnPush Strategy**: Use ChangeDetectionStrategy.OnPush where possible
2. **TrackBy Functions**: Implement trackBy for *ngFor loops
3. **Async Pipes**: Use async pipes instead of manual subscriptions
4. **Virtual Scrolling**: For large lists, implement virtual scrolling

### Memory Management

1. **Subscription Cleanup**: Always unsubscribe from observables
2. **Event Listener Cleanup**: Remove event listeners in ngOnDestroy
3. **Component References**: Avoid circular references
4. **Memory Profiling**: Regular memory leak testing

## Performance Budget Enforcement

### CI/CD Integration

Performance budget checks are integrated into the CI/CD pipeline:

- **PR Checks**: Every pull request is validated against performance budgets
- **Build Failures**: Builds fail if budgets are exceeded
- **Performance Reports**: Detailed performance reports are generated
- **Threshold Alerts**: Warnings are displayed for budget violations

### Budget Violation Response

When performance budgets are exceeded:

1. **Immediate Action**: Fix the performance issue
2. **Root Cause Analysis**: Identify what caused the violation
3. **Optimization**: Implement performance optimizations
4. **Budget Review**: Consider if budget thresholds need adjustment
5. **Documentation**: Update performance guidelines if needed

## Performance Testing

### Automated Tests

The library includes comprehensive performance tests:

```typescript
describe('Performance Tests', () => {
  it('should render within 50ms', async () => {
    const startTime = performance.now();
    fixture.detectChanges();
    await fixture.whenStable();
    const endTime = performance.now();
    
    expect(endTime - startTime).toBeLessThan(50);
  });
  
  it('should not leak memory', () => {
    // Memory leak testing
  });
});
```

### Manual Testing

1. **Bundle Analysis**: Use webpack-bundle-analyzer for detailed analysis
2. **Performance Profiling**: Use browser dev tools for runtime analysis
3. **Memory Profiling**: Use memory profiler to detect leaks
4. **Load Testing**: Test with large datasets and rapid state changes

## Performance Metrics Dashboard

### Current Metrics

- **Bundle Size**: 124 KB (raw), 15.9 KB (gzipped)
- **Component Count**: 15 components
- **Dependency Count**: 7 core dependencies
- **Test Coverage**: 87.41% lines, 80.82% branches

### Performance Trends

Monitor these metrics over time:

- Bundle size growth rate
- Render time trends
- Memory usage patterns
- Test performance metrics

## Best Practices

### Development

1. **Performance First**: Consider performance implications from the start
2. **Regular Monitoring**: Run performance checks frequently
3. **Incremental Testing**: Test performance with each change
4. **Documentation**: Document performance characteristics

### Code Review

1. **Performance Review**: Include performance in code review checklist
2. **Budget Awareness**: Ensure reviewers understand performance budgets
3. **Optimization Suggestions**: Suggest performance improvements
4. **Threshold Validation**: Verify changes don't exceed budgets

### Release Process

1. **Pre-release Testing**: Run full performance test suite
2. **Budget Validation**: Ensure all budgets are met
3. **Performance Regression**: Check for performance regressions
4. **Documentation Update**: Update performance metrics

## Troubleshooting

### Common Issues

1. **Bundle Size Growth**: Identify new dependencies or code additions
2. **Render Performance**: Check for inefficient change detection
3. **Memory Leaks**: Look for uncleaned subscriptions or event listeners
4. **Test Failures**: Investigate performance test failures

### Performance Debugging

1. **Bundle Analysis**: Use bundle analyzer to identify large chunks
2. **Performance Profiling**: Use browser dev tools for runtime analysis
3. **Memory Profiling**: Use memory profiler to detect leaks
4. **Load Testing**: Test with realistic data volumes

## Resources

- [Angular Performance Guide](https://angular.io/guide/performance-checklist)
- [Webpack Bundle Analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer)
- [Chrome DevTools Performance](https://developers.google.com/web/tools/chrome-devtools/evaluate-performance)
- [Memory Profiling](https://developers.google.com/web/tools/chrome-devtools/memory-problems)
