Skip to content

perf: skip Console.Out/Err FlushAsync when no output captured #5712

Description

@thomhurst

Summary

Every test unconditionally awaits two FlushAsync calls in the finally block, producing two extra async state machines per test for the common case where nothing was written to stdout/stderr. Estimated ~1.5-2% CPU reduction, -2 state machines per test.

Evidence

TUnit.Engine/Services/TestExecution/TestCoordinator.cs:141-151:

finally
{
    await Console.Out.FlushAsync();
    await Console.Error.FlushAsync();
    ...
}

CPU-sampling trace shows AsyncMethodBuilderCore.Start at 16.39% inclusive / 2.93% self — test execution dispatches dozens of state machines per test, and these two are unconditionally created even when output redirection captured nothing.

Proposed fix

  • Have the output interceptor set a HasCapturedOutput flag on the context when it first writes.
  • Only flush when the flag is set.

Expected impact

  • ~1.5-2% CPU.
  • Removes 2 async state machines per test.

Metadata

Metadata

Assignees

No one assigned

    Labels

    .NETPull requests that update .net codeenhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions