Skip to content

Commit

Permalink
Avoid allocations when advice doesn't remove any attributes (#6629)
Browse files Browse the repository at this point in the history
  • Loading branch information
jack-berg authored Aug 8, 2024
1 parent b53c48a commit d16ba00
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,28 @@ final class AdviceAttributesProcessor extends AttributesProcessor {

@Override
public Attributes process(Attributes incoming, Context context) {
// Exit early to avoid allocations if the incoming attributes do not have extra keys to be
// filtered
if (!hasExtraKeys(incoming)) {
return incoming;
}
AttributesBuilder builder = incoming.toBuilder();
builder.removeIf(key -> !attributeKeys.contains(key));
return builder.build();
}

/** Returns true if {@code attributes} has keys not contained in {@link #attributeKeys}. */
private boolean hasExtraKeys(Attributes attributes) {
boolean[] result = {false};
attributes.forEach(
(key, value) -> {
if (!result[0] && !attributeKeys.contains(key)) {
result[0] = true;
}
});
return result[0];
}

@Override
public boolean usesContext() {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@ void doesNotUseContext() {
assertThat(new AdviceAttributesProcessor(emptyList()).usesContext()).isFalse();
}

@Test
void noExtraAttributes() {
AttributesProcessor processor =
new AdviceAttributesProcessor(asList(stringKey("abc"), stringKey("def")));

Attributes result =
processor.process(
Attributes.builder().put(stringKey("abc"), "abc").put(stringKey("def"), "def").build(),
Context.root());

assertThat(result).containsOnly(entry(stringKey("abc"), "abc"), entry(stringKey("def"), "def"));
}

@Test
void removeUnwantedAttributes() {
AttributesProcessor processor =
Expand Down

0 comments on commit d16ba00

Please sign in to comment.