Skip to content

refactor: optimize action Execute() allocations using collection expressions #113

@mcj-coder

Description

@mcj-coder

Context

Actions are executed in hot paths (potentially hundreds of NPCs per tick). Current implementation allocates a new List<IGameEvent> on every execution.

Current Implementation

public IReadOnlyList<IGameEvent> Execute(...)
{
    var events = new List<IGameEvent>();  // Allocation on every call
    // ...
    return events;
}

Proposed Solution

Use C# 12 collection expressions for zero-allocation fixed-size collections:

// RestAction (2 events)
return [
    new NeedChangedEvent(...),
    new NeedChangedEvent(...)
];

// EatAction (1 event)
return [new NeedChangedEvent(...)];

Benefits

  • Zero allocation for single-element collections
  • Minimal allocation for fixed-size collections
  • More readable and concise
  • Better performance in hot paths

Files to Update

  • src/FantasyRpgWorld.Core/Actions/RestAction.cs
  • src/FantasyRpgWorld.Core/Actions/EatAction.cs
  • src/FantasyRpgWorld.Core/Actions/WorkAction.cs

Acceptance Criteria

  • All three actions use collection expressions
  • All existing tests pass
  • Zero warnings build

Related

Identified in PR #112 review by .NET Specialist
Part of Epic 3: NPC Decision Making

Labels

  • type:refactor
  • priority:medium
  • area:performance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions