Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid allocations when advice doesn't remove any attributes #6629

Merged
merged 1 commit into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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};
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This little trick allows you to update state from inside a lambda without an atomic variable.

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
Loading