Skip to content

perf: collapse triple OfType().FirstOrDefault() into single foreach in JUnitXmlWriter #6052

Description

@thomhurst

TUnit.Engine/Xml/JUnitXmlWriter.cs:183-197 allocates three OfType<T> iterators per test write, each re-iterating testNode.Properties:

var stateProperty = testNode.Properties.AsEnumerable()
    .OfType<TestNodeStateProperty>().FirstOrDefault();

var timingProperty = testNode.Properties.AsEnumerable()
    .OfType<TimingProperty>().FirstOrDefault();

var testMethodIdentifier = testNode.Properties.AsEnumerable()
    .OfType<TestMethodIdentifierProperty>().FirstOrDefault();

Same pattern at :349-354.

Single-pass alternative:

TestNodeStateProperty? stateProperty = null;
TimingProperty? timingProperty = null;
TestMethodIdentifierProperty? testMethodIdentifier = null;
foreach (var prop in testNode.Properties)
{
    if (stateProperty is null && prop is TestNodeStateProperty s) stateProperty = s;
    else if (timingProperty is null && prop is TimingProperty t) timingProperty = t;
    else if (testMethodIdentifier is null && prop is TestMethodIdentifierProperty m) testMethodIdentifier = m;
    if (stateProperty is not null && timingProperty is not null && testMethodIdentifier is not null) break;
}

Removes 3 iterator allocations + 2 redundant traversals per test.

Why hot: Every test result when JUnit reporter is enabled.
TFM: No gating.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions