Skip to content

Optimize MessageDifferencer::TreatAsSet time complexity to O(N * K)#28785

Draft
copybara-service[bot] wants to merge 1 commit into
mainfrom
test_952878430
Draft

Optimize MessageDifferencer::TreatAsSet time complexity to O(N * K)#28785
copybara-service[bot] wants to merge 1 commit into
mainfrom
test_952878430

Conversation

@copybara-service

@copybara-service copybara-service Bot commented Jul 23, 2026

Copy link
Copy Markdown

Optimize MessageDifferencer::TreatAsSet time complexity to O(N * K)

Optimizes MessageDifferencer::TreatAsSet() repeated field matching by using
hash map lookup (GetRepeatedElementHash) for unmatched elements.

Previously, set matching performed O(N^2 * K) element-pair comparisons. With
hash map lookup, set matching executes in average O(N * K) time complexity.
Updated documentation in message_differencer.h and added
TreatAsSet_LargeUnorderedSet test case to message_differencer_unittest.cc.

Benchmark Scaling (Old O(N^2) vs. New O(N)):

Elements (N) Old Runtime (ms) New Runtime (ms) Speedup
N = 10 0.006 ms 0.005 ms 1.2x
N = 50 0.102 ms 0.033 ms 3.1x
N = 100 0.357 ms 0.041 ms 8.8x
N = 500 8.679 ms 0.195 ms 44.5x
N = 1,000 33.50 ms 0.387 ms 86.6x
N = 5,000 842.48 ms 1.930 ms 436.5x
N = 10,000 3325.82 ms 3.982 ms 835.2x speedup

Optimizes MessageDifferencer::TreatAsSet() repeated field matching by using
hash map lookup (GetRepeatedElementHash) for unmatched elements.

Previously, set matching performed O(N^2 * K) element-pair comparisons. With
hash map lookup, set matching executes in average O(N * K) time complexity.
Updated documentation in message_differencer.h and added
TreatAsSet_LargeUnorderedSet test case to message_differencer_unittest.cc.

Benchmark Scaling (Old O(N^2) vs. New O(N)):
  Elements (N) | Old Runtime (ms) | New Runtime (ms) | Speedup
  ------------ | ---------------- | ---------------- | -------
  N = 10       | 0.006 ms         | 0.005 ms         | 1.2x
  N = 50       | 0.102 ms         | 0.033 ms         | 3.1x
  N = 100      | 0.357 ms         | 0.041 ms         | 8.8x
  N = 500      | 8.679 ms         | 0.195 ms         | 44.5x
  N = 1,000    | 33.50 ms         | 0.387 ms         | 86.6x
  N = 5,000    | 842.48 ms        | 1.930 ms         | 436.5x
  N = 10,000   | 3325.82 ms       | 3.982 ms         | 835.2x speedup

PiperOrigin-RevId: 952878430
@copybara-service copybara-service Bot changed the title Internal change Optimize MessageDifferencer::TreatAsSet time complexity to O(N * K) Jul 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant