Tier 1 Series 5

5D: Loop Efficiency

Pilot Record
Student Profile
"If a mechanic has to inspect 1,000 bolts every second, they don't pick up each bolt, look at it, and put it back in a different pile. They run their hands down the line and check them in place. If your AI uses complex Enumerator Loops for simple data lists, you've created Garbage Collection Drag. A skilled Engineer audits for Index Speed."

The Concept: For vs. Foreach

In C#, a foreach loop is readable, but it creates an "Enumerator" object behind the scenes to track its progress. While this is fine for occasional tasks, doing it every frame with large collections can create "Garbage" that Unity's memory manager has to clean up later.

The Performance Champ: The for (int i = 0...) loop is the fastest because it uses a direct memory index and creates zero memory garbage.
Readability Choice: Use foreach for complex logic that only runs once (like loading a level).
Collection Type: Use for loops exclusively for Arrays and Lists in high-frequency methods like Update() or FixedUpdate().
Red Flag Detected

The AI Trap: "The Garbage Generator"

You ask the AI: "Update the positions of all 500 projectiles in flight."

// AI-Generated Code: Clean but potentially "Trashy"
void Update() {
    // Audit Fail: This creates an Enumerator every single frame.
    // Across 500 items, this builds up "Memory Garbage."
    foreach (Projectile p in activeProjectiles) {
        p.AdvancePosition();
    }
}

This is "Memory Pollution." Every time the Garbage Collector runs to clean up those Enumerators, the game might stutter for a few milliseconds. A professional pilot demands "Stutter-Free" flight by using index-based iteration.

Elite Telemetry

Research shows "Elite" teams achieve 15% faster lead times by keeping AI on a "very tight leash."

  • Small Batches Solving one problem at a time prevents logic drift.
  • Modular Design Localizing the "blast radius" of AI changes.
  • Tight Loops Rapid iteration with constant code review.

The Mechanic's Correction

Corrective Protocol
// Corrected: Zero allocations. Maximum speed.
void Update() {
    // Audit Pass: Direct index access is memory-clean.
    for (int i = 0; i < activeProjectiles.Count; i++) {
        activeProjectiles[i].AdvancePosition();
    }
}
Your Pilot Command
> Optimize networking by using RPCs only for state-changing events.
Next Mission
Memory Leaks