# Performance Budget - HTML Chess Game

## Executive Summary

This document establishes comprehensive performance budgets for all components of the HTML chess game. These budgets serve as hard limits to ensure optimal user experience across all device types and network conditions.

**Budget Philosophy**: "Performance is a feature, not an afterthought"

---

## 1. Overall Performance Targets

### Critical Web Vitals

| Metric | Target | Good | Warning | Critical |
|--------|--------|------|---------|----------|
| **First Contentful Paint (FCP)** | <500ms | <1s | <2s | >2s |
| **Largest Contentful Paint (LCP)** | <1s | <2.5s | <4s | >4s |
| **Time to Interactive (TTI)** | <1s | <2s | <3.5s | >3.5s |
| **Total Blocking Time (TBT)** | <100ms | <300ms | <600ms | >600ms |
| **Cumulative Layout Shift (CLS)** | <0.05 | <0.1 | <0.25 | >0.25 |
| **First Input Delay (FID)** | <10ms | <100ms | <300ms | >300ms |

### Performance Score Targets

| Metric | Desktop | Mobile | Tool |
|--------|---------|--------|------|
| **Lighthouse Performance** | >95 | >90 | Chrome DevTools |
| **WebPageTest Grade** | A | A | WebPageTest.org |
| **PageSpeed Insights** | >95 | >90 | Google PSI |

---

## 2. Bundle Size Budget

### Total Budget: 150KB Gzipped (500KB Uncompressed)

#### Breakdown by Asset Type

| Asset Type | Budget (Uncompressed) | Budget (Gzipped) | Priority |
|------------|----------------------|------------------|----------|
| **HTML** | 5KB | 2KB | Critical |
| **Critical CSS** | 8KB (inline) | 3KB | Critical |
| **Deferred CSS** | 20KB | 7KB | High |
| **Core JavaScript** | 100KB | 35KB | Critical |
| **AI Module (lazy)** | 80KB | 28KB | High |
| **UI Module** | 40KB | 14KB | Critical |
| **Utilities** | 30KB | 10KB | Medium |
| **SVG Pieces (sprite)** | 25KB | 12KB | Critical |
| **Sound Effects (lazy)** | 50KB | 20KB | Low |
| **Fonts (system fallback)** | 0KB | 0KB | N/A |
| **TOTAL CRITICAL** | 173KB | 61KB | - |
| **TOTAL WITH AI** | 253KB | 89KB | - |
| **TOTAL WITH SOUNDS** | 303KB | 109KB | - |

#### Component-Level Budget

| Component | Uncompressed | Gzipped | Lines of Code | Complexity |
|-----------|-------------|---------|---------------|------------|
| `ChessBoard.js` | 12KB | 4KB | ~300 | Medium |
| `ChessPiece.js` | 15KB | 5KB | ~350 | Medium |
| `GameEngine.js` | 20KB | 7KB | ~500 | High |
| `MoveValidator.js` | 18KB | 6KB | ~450 | High |
| `MoveGenerator.js` | 16KB | 5.5KB | ~400 | High |
| `GameController.js` | 14KB | 5KB | ~350 | Medium |
| `UIController.js` | 18KB | 6KB | ~450 | Medium |
| `GameHistory.js` | 10KB | 3.5KB | ~250 | Low |
| `ThemeManager.js` | 8KB | 2.5KB | ~200 | Low |
| `Utils.js` | 9KB | 3KB | ~225 | Low |
| **Core Subtotal** | **140KB** | **48.5KB** | **~3,475** | - |
| `AIPlayer.js` | 25KB | 8.5KB | ~600 | High |
| `MoveEvaluator.js` | 22KB | 7.5KB | ~550 | High |
| `SearchAlgorithm.js` | 28KB | 10KB | ~700 | Very High |
| `TranspositionTable.js` | 12KB | 4KB | ~300 | Medium |
| **AI Subtotal** | **87KB** | **30KB** | **~2,150** | - |
| **TOTAL** | **227KB** | **78.5KB** | **~5,625** | - |

#### Code Splitting Strategy

```javascript
// Initial Load (Critical Path) - 61KB gzipped
- index.html (2KB)
- critical.css (3KB inline)
- core-ui.js (35KB) // Board, Pieces, Controller, Validator
- pieces.svg (12KB)

// Lazy Loaded (On Game Start) - 28KB gzipped
- ai-engine.js (28KB) // AI, Evaluator, Search

// Deferred (Progressive Enhancement) - 27KB gzipped
- styles.css (7KB) // Non-critical styles
- sounds.js + audio (20KB) // Sound effects

// Total Initial: 61KB gzipped
// Total With AI: 89KB gzipped
// Total Everything: 116KB gzipped
```

---

## 3. Runtime Performance Budget

### 3.1 Core Game Operations

| Operation | Budget | Measurement | Monitoring |
|-----------|--------|-------------|------------|
| **Move Validation** | <5ms | p95 | Performance.mark() |
| **Legal Move Generation** | <10ms | p95 | Performance.mark() |
| **Execute Move** | <3ms | p99 | Performance.mark() |
| **Undo/Redo Move** | <5ms | p99 | Performance.mark() |
| **Check Detection** | <8ms | p95 | Performance.mark() |
| **Checkmate Detection** | <15ms | p95 | Performance.mark() |
| **Board Render (Full)** | <16ms (60fps) | p95 | RequestAnimationFrame |
| **Board Update (Diff)** | <2ms | p99 | RequestAnimationFrame |
| **Piece Animation** | <250ms | Always | CSS Transitions |

### 3.2 AI Performance Budget

| Difficulty | Depth | Max Time | Nodes Budget | Target Device |
|------------|-------|----------|--------------|---------------|
| **Random** | 0 | <50ms | 100 | All |
| **Beginner** | 2-3 | <200ms | 10,000 | All |
| **Intermediate** | 3-4 | <500ms | 100,000 | Desktop/High-end Mobile |
| **Advanced** | 4-5 | <1s | 500,000 | Desktop/High-end Mobile |
| **Expert** | 5-6 | <2s | 2,000,000 | Desktop Only |
| **Master** | 6-7 | <5s | 5,000,000 | Desktop Only (Optional) |

#### AI Optimization Targets

| Optimization | Improvement Target | Implementation Complexity |
|--------------|-------------------|---------------------------|
| Alpha-Beta Pruning | 90% node reduction | High (8-10 hrs) |
| Move Ordering | 50% additional reduction | Medium (5-6 hrs) |
| Transposition Table | 30% speedup | High (8-10 hrs) |
| Iterative Deepening | Better UX (anytime) | Medium (4-5 hrs) |
| Quiescence Search | Quality (not speed) | High (6-8 hrs) |
| Web Workers | Non-blocking UI | High (6-8 hrs) |

### 3.3 Rendering Performance Budget

| Component | Frame Budget | Target FPS | Max Layout Shift |
|-----------|--------------|------------|------------------|
| **Board Rendering** | <16ms | 60fps | 0 |
| **Piece Animation** | <16ms | 60fps | 0 |
| **Highlight Updates** | <8ms | 120fps | 0 |
| **UI Updates** | <10ms | 100fps | <0.01 |
| **Theme Changes** | <100ms | N/A | <0.05 |
| **Scroll Performance** | <16ms | 60fps | 0 |

#### Rendering Optimization Targets

| Technique | Target Improvement | Browser Support |
|-----------|-------------------|-----------------|
| Virtual DOM / Diffing | 5-10x faster updates | All modern |
| CSS Transform Animations | GPU acceleration | All modern |
| CSS Classes over Inline | 2x faster updates | All |
| DocumentFragment | 3x faster batch | All |
| RequestAnimationFrame | Consistent 60fps | All modern |
| will-change Property | Prevent layout thrash | All modern |

---

## 4. Memory Budget

### 4.1 Heap Memory Budget

| Device Class | Total Budget | Baseline | Game State | AI Cache | UI State |
|--------------|-------------|----------|------------|----------|----------|
| **Desktop (Modern)** | 80MB | 10MB | 5MB | 50MB | 15MB |
| **Desktop (Old)** | 50MB | 10MB | 5MB | 25MB | 10MB |
| **Mobile (High-end)** | 40MB | 8MB | 5MB | 20MB | 7MB |
| **Mobile (Mid-range)** | 25MB | 8MB | 5MB | 8MB | 4MB |
| **Mobile (Low-end)** | 15MB | 5MB | 3MB | 3MB | 4MB |

### 4.2 Component Memory Budget

| Component | Budget | Notes |
|-----------|--------|-------|
| **BoardState** | 2KB | 64 squares + metadata |
| **Move History** | 1KB/move | 50 moves = 50KB |
| **Transposition Table** | 5-50MB | Configurable by device |
| **Move Cache** | 2MB | Recent positions |
| **UI Event Listeners** | 1KB | Delegated events |
| **Animation Buffers** | 5KB | Temporary |
| **DOM Elements** | 3MB | 64 squares + pieces |

### 4.3 Garbage Collection Budget

| Metric | Budget | Monitoring |
|--------|--------|------------|
| **GC Frequency** | <1 per 30s | Performance API |
| **Major GC Pause** | <50ms | Performance API |
| **Minor GC Pause** | <10ms | Performance API |
| **Heap Growth Rate** | <1MB/min | Memory API |
| **Memory Leaks** | 0 | Chrome DevTools |

#### Memory Optimization Techniques

| Technique | Target | Complexity |
|-----------|--------|------------|
| Object Pooling | 20-30% less GC | High (8-10 hrs) |
| Move History Truncation | Prevent growth | Medium (3-4 hrs) |
| Transposition Table Size Limits | Mobile stability | Low (2-3 hrs) |
| Weak References | Auto cleanup | Medium (4-5 hrs) |
| Lazy Evaluation | Reduce allocations | Medium (5-6 hrs) |

---

## 5. Network Performance Budget (Future)

### 5.1 Initial Page Load

| Resource Type | Budget | Caching | Priority |
|---------------|--------|---------|----------|
| **HTML Document** | 5KB | No cache | Highest |
| **Critical CSS** | 3KB (inline) | N/A | Highest |
| **Critical JS** | 35KB | 1 year | Highest |
| **SVG Sprite** | 12KB | 1 year | High |
| **Deferred CSS** | 7KB | 1 year | Medium |
| **AI Module** | 28KB | 1 year | Medium |
| **Sound Files** | 20KB | 1 year | Low |

### 5.2 Network Conditions

| Connection | Target LCP | Target TTI | Max Bundle |
|------------|-----------|-----------|------------|
| **5G** | <300ms | <500ms | 150KB |
| **4G** | <800ms | <1.2s | 150KB |
| **3G** | <2s | <3s | 100KB |
| **Slow 3G** | <5s | <8s | 50KB |
| **Offline** | N/A | Cached | 0KB |

---

## 6. Device-Specific Budgets

### 6.1 Desktop Performance Budget

| Metric | Modern (2020+) | Old (2015-2019) | Ancient (<2015) |
|--------|----------------|-----------------|-----------------|
| **FCP** | <300ms | <500ms | <1s |
| **LCP** | <600ms | <1s | <2s |
| **TTI** | <800ms | <1.5s | <3s |
| **AI Time (Depth 6)** | <500ms | <1s | <2s |
| **Frame Rate** | 60fps | 60fps | 45fps |
| **Bundle Size** | 150KB | 120KB | 80KB |
| **Memory Usage** | 80MB | 50MB | 30MB |

### 6.2 Mobile Performance Budget

| Metric | High-end | Mid-range | Low-end |
|--------|----------|-----------|---------|
| **FCP** | <600ms | <1s | <2s |
| **LCP** | <1.2s | <2s | <3s |
| **TTI** | <1.5s | <2.5s | <4s |
| **AI Time (Depth 4)** | <1s | <2s | <5s |
| **Frame Rate** | 60fps | 45fps | 30fps |
| **Bundle Size** | 120KB | 80KB | 50KB |
| **Memory Usage** | 40MB | 25MB | 15MB |
| **Battery Impact** | <3%/hour | <5%/hour | <8%/hour |

---

## 7. Feature-Specific Budgets

### 7.1 Drag and Drop

| Metric | Budget | Notes |
|--------|--------|-------|
| **Drag Start Latency** | <10ms | Immediate feedback |
| **Drag Update** | <16ms (60fps) | Smooth tracking |
| **Drop Detection** | <5ms | Instant response |
| **Animation** | <250ms | Visual polish |
| **Memory** | <100KB | Temporary state |

### 7.2 Pawn Promotion Dialog

| Metric | Budget | Notes |
|--------|--------|-------|
| **Dialog Open** | <50ms | Instant display |
| **Selection Response** | <10ms | Immediate |
| **Animation** | <200ms | Quick transition |
| **Memory** | <50KB | Temporary UI |

### 7.3 Game History

| Metric | Budget | Notes |
|--------|--------|-------|
| **Add Move** | <2ms | Append operation |
| **Undo/Redo** | <5ms | State restoration |
| **PGN Export** | <50ms | String generation |
| **History Display** | <16ms | List rendering |
| **Memory** | 1KB/move | Linear growth |

### 7.4 Theme Switching

| Metric | Budget | Notes |
|--------|--------|-------|
| **Theme Load** | <100ms | CSS update |
| **Color Update** | <50ms | CSS variables |
| **Piece Sprite Swap** | <200ms | Image loading |
| **Layout Shift** | 0 | No reflow |
| **Memory** | <500KB | Theme data |

---

## 8. Optimization Implementation Budget

### 8.1 Time Investment by Priority

| Priority | Total Hours | ROI | Status |
|----------|-------------|-----|--------|
| **CRITICAL** | 28-36 hrs | 10-100x improvement | Required |
| **HIGH** | 41-50 hrs | 3-5x improvement | Recommended |
| **MEDIUM** | 14-18 hrs | 1.5-2x improvement | Optional |
| **TOTAL** | 83-104 hrs | 15-200x improvement | - |

### 8.2 Critical Optimizations (Must-Have)

| Optimization | Time | Impact | Dependency |
|--------------|------|--------|------------|
| **Alpha-Beta Pruning** | 8-10 hrs | 10-100x AI speed | None |
| **Web Workers** | 6-8 hrs | Non-blocking UI | None |
| **DOM Diffing** | 6-8 hrs | 5-10x render speed | None |
| **CSS Transforms** | 4-5 hrs | GPU acceleration | None |
| **Code Splitting** | 4-5 hrs | 2x faster load | Build tools |
| **TOTAL** | **28-36 hrs** | **Essential** | **Minimal** |

### 8.3 High Priority Optimizations (Should-Have)

| Optimization | Time | Impact | Dependency |
|--------------|------|--------|------------|
| **Move Ordering** | 5-6 hrs | 2-3x AI speed | Alpha-Beta |
| **Transposition Table** | 8-10 hrs | 1.5-2x AI speed | Hash functions |
| **Bundle Optimization** | 8-10 hrs | 50% smaller | Build pipeline |
| **Incremental Eval** | 10-12 hrs | 1.5x AI speed | Evaluator |
| **Mobile Optimization** | 10-12 hrs | Mobile support | Device detection |
| **TOTAL** | **41-50 hrs** | **Significant** | **Moderate** |

### 8.4 Medium Priority Optimizations (Nice-to-Have)

| Optimization | Time | Impact | Dependency |
|--------------|------|--------|------------|
| **Iterative Deepening** | 4-5 hrs | Better UX | Alpha-Beta |
| **Object Pooling** | 8-10 hrs | Reduced GC | None |
| **SVG Optimization** | 2-3 hrs | 50% smaller | SVGO tool |
| **TOTAL** | **14-18 hrs** | **Polish** | **Low** |

---

## 9. Performance Monitoring Strategy

### 9.1 Development Metrics

| Metric | Tool | Frequency | Alert Threshold |
|--------|------|-----------|-----------------|
| **Bundle Size** | Webpack | Every build | >150KB gzipped |
| **Test Performance** | Jest | Every run | >5s total |
| **Lighthouse Score** | CLI | Pre-commit | <90 |
| **Memory Leaks** | Chrome DevTools | Weekly | Any detected |
| **Code Coverage** | Jest | Every push | <80% |

### 9.2 Production Metrics (Future)

| Metric | Tool | Sampling | P95 Target |
|--------|------|----------|------------|
| **Real User FCP** | RUM | 1% | <1s |
| **Real User LCP** | RUM | 1% | <2s |
| **Real User TTI** | RUM | 1% | <2.5s |
| **AI Response Time** | Custom | 100% | <2s |
| **Error Rate** | Sentry | 100% | <0.1% |
| **Crash Rate** | Sentry | 100% | <0.01% |

### 9.3 Performance Testing

```javascript
// Performance Test Suite
describe('Performance Budget', () => {
  it('should render board in <16ms', () => {
    performance.mark('render-start');
    renderBoard();
    performance.mark('render-end');
    const duration = performance.measure('render', 'render-start', 'render-end');
    expect(duration.duration).toBeLessThan(16);
  });

  it('should calculate AI move in <1s (depth 5)', () => {
    const start = performance.now();
    const move = ai.calculateMove(position, { depth: 5 });
    const duration = performance.now() - start;
    expect(duration).toBeLessThan(1000);
  });

  it('should validate move in <5ms', () => {
    performance.mark('validate-start');
    const isValid = validator.isMoveLegal(from, to, gameState);
    performance.mark('validate-end');
    const duration = performance.measure('validate', 'validate-start', 'validate-end');
    expect(duration.duration).toBeLessThan(5);
  });

  it('should maintain 60fps during animation', async () => {
    const frameRates = await measureFrameRate(() => animateMove(from, to));
    expect(Math.min(...frameRates)).toBeGreaterThan(58);
  });

  it('should use <50MB memory on mobile', () => {
    if (isMobile()) {
      const memUsage = performance.memory.usedJSHeapSize / 1024 / 1024;
      expect(memUsage).toBeLessThan(50);
    }
  });
});
```

---

## 10. Budget Violation Response Plan

### 10.1 Budget Exceeded Protocol

| Violation Severity | Response | Timeline |
|--------------------|----------|----------|
| **<10% Over** | Document and plan fix | Next sprint |
| **10-25% Over** | Immediate investigation | 24 hours |
| **25-50% Over** | Block merge, optimize | Before merge |
| **>50% Over** | Critical fix required | Immediate |

### 10.2 Performance Regression Handling

```javascript
// Pre-commit hook
if (bundleSize > BUDGET.bundleSize * 1.1) {
  console.error('❌ Bundle size exceeded budget by >10%');
  console.error(`Current: ${bundleSize}KB | Budget: ${BUDGET.bundleSize}KB`);
  process.exit(1);
}

if (lighthouseScore < 90) {
  console.warn('⚠️  Lighthouse score below threshold');
  console.warn(`Current: ${lighthouseScore} | Target: 90+`);
}
```

### 10.3 Optimization Priority Matrix

When budgets are exceeded, prioritize fixes by:

1. **Impact**: User-facing performance issues first
2. **Effort**: Quick wins before complex refactors
3. **Risk**: Low-risk optimizations before risky changes
4. **Dependency**: Independent fixes before dependent ones

---

## 11. Performance Budget Summary

### Critical Metrics (Must Meet)

| Metric | Budget | Priority |
|--------|--------|----------|
| **Lighthouse Score** | >90 | Critical |
| **Initial Load (gzipped)** | <61KB | Critical |
| **FCP** | <500ms | Critical |
| **TTI** | <1s | Critical |
| **AI Response (Depth 5)** | <1s | Critical |
| **Frame Rate** | 60fps | Critical |
| **Memory (Desktop)** | <80MB | Critical |
| **Memory (Mobile)** | <40MB | Critical |

### Success Criteria

✅ **Pass**: All critical budgets met
⚠️  **Warning**: 1-2 budgets exceeded by <10%
❌ **Fail**: Any budget exceeded by >10% or 3+ budgets exceeded

---

## 12. Long-Term Performance Goals

### Phase 1: MVP (Current)
- Meet all critical budgets
- 90+ Lighthouse score
- 60fps on desktop
- Basic mobile support

### Phase 2: Optimization (2-3 weeks)
- 95+ Lighthouse score
- 60fps on high-end mobile
- <50KB initial bundle
- Advanced AI optimizations

### Phase 3: Excellence (1-2 months)
- 98+ Lighthouse score
- 60fps on all devices
- <30KB initial bundle
- Best-in-class performance

---

## Budget Maintenance

This performance budget is a living document and should be:

1. **Reviewed**: Every sprint
2. **Updated**: When requirements change
3. **Enforced**: On every commit
4. **Celebrated**: When exceeded in positive direction

**Remember**: "A performance budget is only useful if it's enforced."

---

**Document Version**: 1.0.0
**Last Updated**: 2025-11-22
**Owner**: Performance Optimizer Agent
**Review Cycle**: Every Sprint
