Coreclr gc watchdog

From nlelouche/Unity-SkillForge · View interactive version

Coreclr gc watchdog is an AI agent skill from the GitHub repository nlelouche/Unity-SkillForge. Detects, diagnoses, and eliminates Garbage Collector pressure in Unity (CoreCLR). Provides patterns for zero-alloc code, Profiler integration guidance, and a GC budget monitoring protocol.

How to use this skill

Skill file

CoreCLR GC Watchdog

Overview

Unity 6 runs on CoreCLR, a modern .NET runtime with a generational garbage collector. While CoreCLR is more efficient than Mono, uncontrolled GC allocations still cause frame spikes (GC.Collect pauses). This skill audits code for allocation hot-spots, classifies the allocation sources, and applies zero-alloc patterns to eliminate the pressure.

When to Use

GC Pressure Classification

| Allocation Source | Severity | Zero-Alloc Replacement |

|-------------------|----------|------------------------|

| new List<T>() in Update() | 🔴 Critical | Pre-allocate + .Clear() |

| LINQ (.Where(), .Select()) in hot path | 🔴 Critical | for loop |

| string + concatenation in loop | 🔴 Critical | StringBuilder |

| GetComponent<T>() in Update() | 🟠 High | Cache in Awake() |

| Boxing value types (int as object) | 🟠 High | Generic methods / IEquatable<T> |

| Delegates / lambdas (allocation on capture) | 🟡 Medium | Cache delegate as field |

| params object[] variadic args | 🟡 Medium | Overloads or Span<T> |

| foreach on non-generic IEnumerable | 🟢 Low | Use generic IEnumerable<T> |

Profiler Integration Workflow

1. Open Window → Analysis → Profiler
2. Record a gameplay session (10-30 seconds)
3. Click "GC Alloc" column to sort by allocation size
4. Identify the largest allocating frame
5. Drill into the call stack → find the responsible method
6. Apply the fix pattern from the Classification table above
7. Re-record → verify column shows 0B

Key Profiler Markers to Watch

Procedure

  1. Profile First: Never optimize by guessing. Use the Profiler to pinpoint the hot frame.
  2. Identify Source: Read the call stack for the GC.Alloc marker.
  3. Classify: Match to the GC Pressure table.
  4. Apply Pattern: Use the zero-alloc replacement.
  5. Re-Validate: Record again to confirm 0B in that callsite.

Best Practices

Few-Shot Examples

Example 1: Pre-allocating a List

// ❌ BEFORE — allocates every frame
private void Update()
{
    var enemies = new List<Enemy>(); // GC ALLOC!
    FindEnemiesInRange(enemies);
}

// ✅ AFTER — zero alloc
private readonly List<Enemy> _enemyBuffer = new(32);

private void Update()
{
    _enemyBuffer.Clear(); // reuse, no alloc
    FindEnemiesInRange(_enemyBuffer);
}

Example 2: Caching a Delegate

// ❌ BEFORE — lambda captured as new alloc every call
private void SubscribeEvents()
{
    _button.onClick.AddListener(() => OnButtonClicked()); // alloc!
}

// ✅ AFTER — cache the delegate
private readonly UnityAction _onButtonClicked;

private void Awake() => _onButtonClicked = OnButtonClicked;
private void OnEnable()  => _button.onClick.AddListener(_onButtonClicked);
private void OnDisable() => _button.onClick.RemoveListener(_onButtonClicked);

Example 3: Span for Temporary Data

// ✅ Stack-allocated buffer — zero heap alloc
private void ProcessHits(int hitCount)
{
    Span<RaycastHit> hits = stackalloc RaycastHit[hitCount];
    Physics.RaycastNonAlloc(transform.position, Vector3.forward, /* ... */);
    // Process hits without any heap allocation
}

TDD Contract

⚠️ Legacy Skill — Refactor Pending

Este skill NO tiene tests automatizados aún. El siguiente boilerplate es un punto de partida.

// Escribe estos tests ANTES de implementar:

// Test 1: should [expected behavior] when [condition]
[Test]
public void CoreclrGcWatchdog_Should{ExpectedBehavior}_When{Condition}()
{{
    // Arrange
    // TODO: Setup test fixtures
    
    // Act
    // TODO: Execute system under test
    
    // Assert
    Assert.Fail("Not implemented — write test first");
}}

// Test 2: should handle [edge case]
[Test]
public void CoreclrGcWatchdog_ShouldHandle{EdgeCase}()
{{
    // Arrange
    // TODO: Setup edge case scenario
    
    // Act
    // TODO: Execute
    
    // Assert
    Assert.Fail("Not implemented");
}}

// Test 3: should throw when [invalid input]
[Test]
public void CoreclrGcWatchdog_ShouldThrow_When{InvalidInput}()
{{
    // Arrange
    var invalidInput = default;
    
    // Act & Assert
    Assert.Throws<Exception>(() => {{ /* execute */ }});
}}

Pasos para completar el TDD:

  1. Descomenta los tests above
  2. Implementa la funcionalidad mínima para que compile
  3. Ejecuta los tests — deben fallar (RED)
  4. Implementa la funcionalidad real
  5. Verifica que los tests pasen (GREEN)
  6. Refactorea manteniendo los tests verdes

Nota: Este skill fue marcado como tdd_first: false durante la auditoría v2.0.1. La sección TDD fue agregada automáticamente pero requiere customización manual para reflejar el comportamiento real del skill.

Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.