Skip to content

Commit

Permalink
Improve LogSite equality checking to avoid unneeded allocations
Browse files Browse the repository at this point in the history
RELNOTES=n/a
PiperOrigin-RevId: 700073681
  • Loading branch information
nick-someone authored and Flogger Team committed Nov 25, 2024
1 parent 43858aa commit fc6e93b
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion api/src/main/java/com/google/common/flogger/LogSite.java
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,9 @@ public String getClassName() {
// earlier could cost work in cases where the log statement is dropped. We could cache the
// result somewhere, but in the default Fluent Logger backend, this method is actually only
// called once anyway when constructing the LogRecord instance.

// See implementation comments for internalNamesCompatible for more details when the internal
// class name is not in fact a slash-separated class name.
return internalClassName.replace('/', '.');
}

Expand Down Expand Up @@ -201,11 +204,39 @@ public boolean equals(@Nullable Object obj) {
return methodName.equals(other.methodName)
&& encodedLineNumber == other.encodedLineNumber
// Check classname last because it isn't cached
&& getClassName().equals(other.getClassName());
&& internalNamesCompatible(internalClassName, other.internalClassName);
}
return false;
}

// The compile-time injection mechanism uses a slash-separated class name, but
// unfortunately some users have been using dot-separated class names. We need to be able to
// make these equivalent, but want to avoid allocating/copying strings.
@SuppressWarnings("ReferenceEquality")
private static boolean internalNamesCompatible(String s1, String s2) {
if (s1 == s2) { // We expect most internal class names to be interned.
return true;
}

if (s1.length() != s2.length()) {
return false;
}

for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) {
continue;
}
if (s1.charAt(i) == '/' && s2.charAt(i) == '.') {
continue;
}
if (s1.charAt(i) == '.' && s2.charAt(i) == '/') {
continue;
}
return false;
}
return true;
}

@Override
public int hashCode() {
if (hashcode == 0) {
Expand Down

0 comments on commit fc6e93b

Please sign in to comment.