Memory profiler expert

From nlelouche/Unity-SkillForge · View interactive version

Memory profiler expert is an AI agent skill from the GitHub repository nlelouche/Unity-SkillForge. Unity memory and performance profiling expertise for identifying bottlenecks and optimizing allocations.

How to use this skill

Skill file

Memory & Performance Profiler Expert

Overview

Unity profiling expertise for identifying performance bottlenecks, memory leaks, and GC allocation issues. Essential for optimization.

When to Use

Profiling Tools

┌─────────────────────────────────────────────────────────────┐
│                   UNITY PROFILER MODULES                    │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  CPU PROFILER           MEMORY PROFILER                     │
│  ┌──────────────┐      ┌──────────────┐                    │
│  │ Timeline     │      │ Snapshots    │                    │
│  │ Hierarchy    │      │ Diff Compare │                    │
│  │ Raw Samples  │      │ Object Types │                    │
│  └──────────────┘      └──────────────┘                    │
│                                                             │
│  GPU PROFILER           GC ALLOC                           │
│  ┌──────────────┐      ┌──────────────┐                    │
│  │ Draw Calls   │      │ Per Frame    │                    │
│  │ Batches      │      │ Call Stacks  │                    │
│  │ Fill Rate    │      │ Type Names   │                    │
│  └──────────────┘      └──────────────┘                    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Common Bottlenecks

| Issue | Symptoms | Solution |

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

| GC Spikes | Stutters at intervals | Object pooling, cache |

| Memory Leak | Memory grows | Release, weak refs |

| Main Thread | Low FPS | Jobs, async |

| Draw Calls | GPU bound | Batching, atlasing |

Key Metrics

| Metric | Target (Mobile) | Target (Desktop) |

|--------|:---------------:|:----------------:|

| Frame Time | <16ms (60fps) | <8ms (120fps) |

| GC Alloc/Frame | 0KB | 0KB |

| Draw Calls | <100 | <500 |

| Triangles | <100K | <1M |

Best Practices

Few-Shot Examples

Example 1: Allocation Tracker

User: "Find memory allocations."

Agent:

#if DEVELOPMENT_BUILD || UNITY_EDITOR
public class AllocationTracker : MonoBehaviour
{
    private long _lastTotalMemory;
    private int _allocsPerSecond;
    private float _timer;
    
    private void Update()
    {
        _timer += Time.deltaTime;
        
        long current = GC.GetTotalMemory(false);
        if (current > _lastTotalMemory)
        {
            _allocsPerSecond++;
        }
        _lastTotalMemory = current;
        
        if (_timer >= 1f)
        {
            if (_allocsPerSecond > 10)
            {
                Debug.LogWarning($"High allocations: {_allocsPerSecond}/sec");
            }
            _allocsPerSecond = 0;
            _timer = 0;
        }
    }
}
#endif

Example 2: Frame Time Monitor

User: "Display performance stats."

Agent:

public class PerformanceHUD : MonoBehaviour
{
    private float _deltaTime;
    
    private void Update()
    {
        _deltaTime += (Time.unscaledDeltaTime - _deltaTime) * 0.1f;
    }
    
    private void OnGUI()
    {
        float fps = 1.0f / _deltaTime;
        float ms = _deltaTime * 1000f;
        
        string text = $"{fps:0.} FPS ({ms:0.0}ms)";
        
        var style = new GUIStyle();
        style.fontSize = 24;
        style.normal.textColor = fps < 30 ? Color.red : 
                                  fps < 60 ? Color.yellow : Color.green;
        
        GUI.Label(new Rect(10, 10, 200, 30), text, style);
    }
}

Example 3: Memory Snapshot Comparison

User: "Check for memory leaks."

Agent:

Workflow:
1. Play game to main menu
2. Memory Profiler → Take Snapshot (Baseline)
3. Play through game loop
4. Return to main menu
5. Force GC: System.GC.Collect()
6. Take Snapshot (After)
7. Compare → Look for:
   - New objects not released
   - Growing collections
   - Texture/mesh duplicates

Profiling Checklist


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 MemoryProfilerExpert_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 MemoryProfilerExpert_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 MemoryProfilerExpert_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.