rpc/gasprice: optimize using kth algorithm #18549
Open
+47
−16
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR makes the gas price oracle faster.
Right now, Erigon collects sampled transaction tips into a heap and then repeatedly pops elements until it reaches the requested percentile. This works correctly, but it does extra work because many elements are popped and discarded.
In practice, the oracle only needs one value (the percentile), not a fully ordered list.
This PR replaces the repeated heap pops with a k-th element (QuickSelect) algorithm, which directly finds the needed percentile value.
The result is the same, but the work done is much smaller.
Test/Benchmark Cases:
Benchmarks measure only the percentile calculation logic, excluding block loading, RPC calls, and other unrelated work.
Small input (20 values)
(24,143 - 19,329) / 24,143 ≈ 20%
Realistic input (~3600 values)
This matches real usage (about 20 blocks with ~180 sampled transactions per block).
(554,593 - 197,786) / 554,593 ≈ 64%