[Metrics] Reduce CPU consumption of metrics creation #9735
Merged
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.
Motivation
String.format
is consuming most CPU when generating metrics:(Flamegraph from Pulsar user, using Pulsar 2.7.0)
Besides direct CPU consumption, it creates a lot of garbage which then causes more CPU being spent in GC.
Modifications
It is possible to get rid of the key creation and avoid String.format calls and String object allocation, by using a similar approach as @rdhabalia used in NamespaceStats:
pulsar/pulsar-broker/src/main/java/org/apache/pulsar/broker/stats/NamespaceStats.java
Lines 46 to 63 in cc64889
Since there are multiple sets of buckets, there is a need for a class that handles the logic.