Skip to content

[efficiency-improver] perf: eliminate redundant ContainsKey in IPC deserialization hot path - #16170

Merged
Azat Mukhametshin (azat-msft) merged 1 commit into
mainfrom
efficiency/ipc-deserialize-single-lookup-9e6955e3e3eebfb1
Jun 27, 2026
Merged

Azat Mukhametshin (azat-msft) merged 1 commit into
mainfrom
efficiency/ipc-deserialize-single-lookup-9e6955e3e3eebfb1

Conversation

@nohwnd

Copy link
Copy Markdown
Member

Goal and Rationale

Eliminate redundant dictionary hash lookups in the IPC deserialization hot path (JsoniteConvert). Both DeserializeTestCase and DeserializeTestResult used ContainsKey to detect the wire-format version ("flat" vs "nested"), then immediately repeated the same key lookup with TryGetValue — hashing the same key twice per test case/result received over IPC.

Focus area: Network & I/O Efficiency (IPC receive path)


Approach

  1. DeserializeTestCase — replaced dict.ContainsKey("FullyQualifiedName") with dict.TryGetValue("FullyQualifiedName", out var fqnFlat), reusing fqnFlat directly instead of a second TryGetValue call on the same key.

  2. DeserializeTestResult — replaced dict.ContainsKey("Outcome") with dict.TryGetValue("Outcome", out var ocFlat), and removed the now-redundant inner if (dict.TryGetValue("Outcome", ...)) guard.

Both changes are semantics-preserving: the flat boolean has the same value, and the extracted value is used identically.


Energy Efficiency Evidence

Proxy metric used: CPU instruction count / hash operations → fewer redundant dictionary hash computations = fewer CPU cycles per test case/result received.

Location Before After
DeserializeTestCase 2 hash lookups for "FullyQualifiedName" per deserialized test case 1 hash lookup
DeserializeTestResult 2 hash lookups for "Outcome" per deserialized test result 1 hash lookup

For a 10 000-test run (discovery + execution):

  • ~20 000 redundant dictionary hash lookups eliminated — 10K in discovery (test cases) + 10K in execution (test results)
  • These are called in the IPC receive loop — every test case discovered and every test result received takes this path

Green Software Foundation Context

  • Hardware Efficiency: fewer CPU instructions per test case received over IPC reduces overall CPU energy per dotnet test invocation. At ecosystem scale (millions of CI runs daily), even small per-invocation reductions accumulate.
  • SCI (Software Carbon Intensity): reduces CPU work per functional unit (test run), lowering the energy term in the SCI equation.

Trade-offs

None. This is a pure refactoring that preserves identical behaviour. The change is a 4-line diff with no added complexity.


Reproducibility

./build.sh
./test.sh -p CommunicationUtilities

Test Status

✅ Build succeeded (0 errors, 0 new warnings from this change)
✅ All 630 Microsoft.TestPlatform.CommunicationUtilities.UnitTests tests passed (net11.0|x64)

Generated by Efficiency Improver · 1.1K AIC · ⌖ 26.4 AIC · ⊞ 45.6K · ◷

Replace ContainsKey + TryGetValue double-hash with a single TryGetValue
call in DeserializeTestCase and DeserializeTestResult. Each test case
and test result received over IPC previously did two dictionary lookups
for the format-detection key ('FullyQualifiedName' / 'Outcome'). Now a
single TryGetValue serves both purposes.

For a 10 000-test run this eliminates ~20 000 redundant dictionary hash
lookups in the IPC receive path.

Co-authored-by: Copilot <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR is a micro-optimization in the CommunicationUtilities IPC deserialization path (JsoniteConvert) to avoid redundant dictionary key lookups during TestCase and TestResult deserialization (hot path for IPC receive).

Changes:

  • In DeserializeTestCase, replaced ContainsKey("FullyQualifiedName") + follow-up lookup with a single TryGetValue, reusing the retrieved value.
  • In DeserializeTestResult, replaced ContainsKey("Outcome") + follow-up lookup with a single TryGetValue, reusing the retrieved value.

@nohwnd Jakub Jareš (nohwnd) left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: JsoniteConvert IPC deserialization optimization

Dimension sweep

Dimension Status Notes
IPC Transport & Protocol Stability ✅ pass Deserialization-only; no wire format touched
Backward Compatibility & Rollback Safety ✅ pass Semantics preserved across all cases
Null Safety & Boundary Validation ⚠️ minor See inline — implicit null-to-0 coercion, same as before
Algorithmic Correctness ✅ pass TryGetValue bool ≡ ContainsKey bool; inner guard removal valid
Cross-TFM & Framework Resolution ✅ pass Correctly scoped to #if !NETCOREAPP (line 4)
Performance i️ info Optimization is real; one fewer hash lookup per call
Acceptance Test Coverage ✅ pass See below

Correctness

Both changes are semantics-preserving. TryGetValue returns true iff the key exists — identical to ContainsKey for any conforming IDictionary implementation. The captured fqnFlat/ocFlat values are used exactly as the old fqn/oc were:

  • DeserializeTestCase: if (fqnFlat != null) guard preserved. ✓
  • DeserializeTestResult: inner guard dropped correctly — it was always true inside if (flat), making it a no-op. See inline comment for the null-edge-case trace.

Test coverage

Better than it looks. SerializationGoldenTests.cs targets net481 (in addition to net11.0), so TestResultRoundTripV2ShouldPreserveKeyProperties and TestCaseRoundTripV2ShouldPreserveKeyProperties exercise the exact Jsonite DeserializeTestCase/DeserializeTestResult flat paths changed here — and both assert field values including Outcome and FullyQualifiedName. No new test is strictly needed for the happy path.

The null-valued-key edge case ("Outcome": null on the wire) isn't tested, but the behavior is unchanged from before, and in practice the IPC protocol never emits a null Outcome.

Performance claim

Valid. One fewer Dictionary<string, object> hash lookup per TestCase/TestResult received over IPC. The magnitude is nanoseconds per call — unmeasured and unmeasurable at the test-run level — but the claim is directionally correct and the change introduces no new allocations.

One nit inline — otherwise looks good :)

🧠 Reviewed by Expert Code Reviewer 🧠

if (flat)
{
if (dict.TryGetValue("Outcome", out var oc)) tr.Outcome = (TestOutcome)Convert.ToInt32(oc, CultureInfo.InvariantCulture);
tr.Outcome = (TestOutcome)Convert.ToInt32(ocFlat, CultureInfo.InvariantCulture);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Null Safety & Boundary Validation / Algorithmic Correctness]

Removing the inner guard is correct — dict.TryGetValue("Outcome", ...) inside if (flat) was always true (key presence is guaranteed by the outer check), so the guard was purely redundant. The new code is semantically identical across all cases:

"Outcome" key value Old result New result
absent — flat=false, block skipped same
present 1 TestOutcome.Passed same
present null Convert.ToInt32(null)=0 → TestOutcome.None same

The null→0 coercion is a Convert.ToInt32(object, IFormatProvider) contract detail (documented: returns 0 when value is null). Old oc and new ocFlat were always on the same path. No behavioral change here.

nit: contrast with DeserializeTestCase line 252 where an explicit if (fqnFlat != null) guard is kept — the asymmetry is intentional (skipping a string assignment vs. defaulting an enum to 0), but a brief inline comment would make the null-tolerance conscious for future readers:

Suggested change
tr.Outcome = (TestOutcome)Convert.ToInt32(ocFlat, CultureInfo.InvariantCulture);
tr.Outcome = (TestOutcome)Convert.ToInt32(ocFlat, CultureInfo.InvariantCulture); // null → 0 (TestOutcome.None) by Convert contract

@nohwnd
Jakub Jareš (nohwnd) marked this pull request as ready for review June 26, 2026 12:02
@nohwnd Jakub Jareš (nohwnd) added the 🚢 Ship it! Add to PRs where owner approves automated PR, but cannot approve because they "wrote it". label Jun 26, 2026

@nohwnd Jakub Jareš (nohwnd) left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: JsoniteConvert IPC deserialization optimization (re-run)

Dimension sweep

Dimension Status Notes
IPC Transport & Protocol Stability ✅ pass Deserialization-only; no wire format change
Backward Compatibility & Rollback Safety ✅ pass Semantics preserved across all key/value combinations
Null Safety & Boundary Validation i️ nit Convert.ToInt32(null)=0 is documented contract; prior inline nit (line 294) still unresolved
Algorithmic Correctness ✅ pass TryGetValue bool ≡ ContainsKey bool; inner guard removal valid
Cross-TFM & Framework Resolution ✅ pass Entire file is #if !NETCOREAPP — change is correctly scoped
Performance i️ info One fewer hash lookup per TestCase/TestResult deserialized; no new allocations

Correctness

Both changes are semantics-preserving under full inspection of the surrounding context:

DeserializeTestCase (line 249): TryGetValue returns true iff the key exists — identical to ContainsKey. The captured fqnFlat is used identically to the prior fqn. The if (fqnFlat != null) guard is preserved. When flat=false, fqnFlat is null but is never read. ✅

DeserializeTestResult (line 291): Same TryGetValue/ContainsKey equivalence. The removed inner guard if (dict.TryGetValue("Outcome", out var oc)) was always true inside if (flat) — key presence is guaranteed by the outer check. Convert.ToInt32(null, InvariantCulture) = 0 = TestOutcome.None matches prior behavior when oc was null. ✅

The flat / !flat dispatch at lines 267 and 310 is unaffected.

Prior inline comment

A nit was posted in the previous review cycle on line 294 suggesting a comment to document the null → 0 (TestOutcome.None) coercion. It remains unresolved and is not a blocking concern.

🧠 Reviewed by Expert Code Reviewer 🧠

🧠 Reviewed by Expert Code Reviewer 🧠

@azat-msft
Azat Mukhametshin (azat-msft) merged commit 9f3151a into main Jun 27, 2026
46 checks passed
@azat-msft
Azat Mukhametshin (azat-msft) deleted the efficiency/ipc-deserialize-single-lookup-9e6955e3e3eebfb1 branch June 27, 2026 09:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agentic-workflows Area: Performance 🚢 Ship it! Add to PRs where owner approves automated PR, but cannot approve because they "wrote it".

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants