Repository navigation
[efficiency-improver] perf: eliminate redundant ContainsKey in IPC deserialization hot path - #16170
Conversation
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]>
There was a problem hiding this comment.
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, replacedContainsKey("FullyQualifiedName")+ follow-up lookup with a singleTryGetValue, reusing the retrieved value. - In
DeserializeTestResult, replacedContainsKey("Outcome")+ follow-up lookup with a singleTryGetValue, reusing the retrieved value.
Jakub Jareš (nohwnd)
left a comment
There was a problem hiding this comment.
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 | 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 alwaystrueinsideif (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); |
There was a problem hiding this comment.
[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:
| tr.Outcome = (TestOutcome)Convert.ToInt32(ocFlat, CultureInfo.InvariantCulture); | |
| tr.Outcome = (TestOutcome)Convert.ToInt32(ocFlat, CultureInfo.InvariantCulture); // null → 0 (TestOutcome.None) by Convert contract |
Jakub Jareš (nohwnd)
left a comment
There was a problem hiding this comment.
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 🧠
Goal and Rationale
Eliminate redundant dictionary hash lookups in the IPC deserialization hot path (
JsoniteConvert). BothDeserializeTestCaseandDeserializeTestResultusedContainsKeyto detect the wire-format version ("flat" vs "nested"), then immediately repeated the same key lookup withTryGetValue— hashing the same key twice per test case/result received over IPC.Focus area: Network & I/O Efficiency (IPC receive path)
Approach
DeserializeTestCase— replaceddict.ContainsKey("FullyQualifiedName")withdict.TryGetValue("FullyQualifiedName", out var fqnFlat), reusingfqnFlatdirectly instead of a secondTryGetValuecall on the same key.DeserializeTestResult— replaceddict.ContainsKey("Outcome")withdict.TryGetValue("Outcome", out var ocFlat), and removed the now-redundant innerif (dict.TryGetValue("Outcome", ...))guard.Both changes are semantics-preserving: the
flatboolean 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.
DeserializeTestCase"FullyQualifiedName"per deserialized test caseDeserializeTestResult"Outcome"per deserialized test resultFor a 10 000-test run (discovery + execution):
Green Software Foundation Context
dotnet testinvocation. At ecosystem scale (millions of CI runs daily), even small per-invocation reductions accumulate.Trade-offs
None. This is a pure refactoring that preserves identical behaviour. The change is a 4-line diff with no added complexity.
Reproducibility
Test Status
✅ Build succeeded (0 errors, 0 new warnings from this change)
✅ All 630
Microsoft.TestPlatform.CommunicationUtilities.UnitTeststests passed (net11.0|x64)