Skip to content

Commit b7f0ef9

Browse files
jack-bergbreedx-splk
authored andcommitted
Avoid allocations when advice doesn't remove any attributes (open-telemetry#6629)
1 parent 74a7ce5 commit b7f0ef9

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/AdviceAttributesProcessor.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,28 @@ final class AdviceAttributesProcessor extends AttributesProcessor {
2323

2424
@Override
2525
public Attributes process(Attributes incoming, Context context) {
26+
// Exit early to avoid allocations if the incoming attributes do not have extra keys to be
27+
// filtered
28+
if (!hasExtraKeys(incoming)) {
29+
return incoming;
30+
}
2631
AttributesBuilder builder = incoming.toBuilder();
2732
builder.removeIf(key -> !attributeKeys.contains(key));
2833
return builder.build();
2934
}
3035

36+
/** Returns true if {@code attributes} has keys not contained in {@link #attributeKeys}. */
37+
private boolean hasExtraKeys(Attributes attributes) {
38+
boolean[] result = {false};
39+
attributes.forEach(
40+
(key, value) -> {
41+
if (!result[0] && !attributeKeys.contains(key)) {
42+
result[0] = true;
43+
}
44+
});
45+
return result[0];
46+
}
47+
3148
@Override
3249
public boolean usesContext() {
3350
return false;

sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/AdviceAttributesProcessorTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,19 @@ void doesNotUseContext() {
2424
assertThat(new AdviceAttributesProcessor(emptyList()).usesContext()).isFalse();
2525
}
2626

27+
@Test
28+
void noExtraAttributes() {
29+
AttributesProcessor processor =
30+
new AdviceAttributesProcessor(asList(stringKey("abc"), stringKey("def")));
31+
32+
Attributes result =
33+
processor.process(
34+
Attributes.builder().put(stringKey("abc"), "abc").put(stringKey("def"), "def").build(),
35+
Context.root());
36+
37+
assertThat(result).containsOnly(entry(stringKey("abc"), "abc"), entry(stringKey("def"), "def"));
38+
}
39+
2740
@Test
2841
void removeUnwantedAttributes() {
2942
AttributesProcessor processor =

0 commit comments

Comments
 (0)