Skip to content

Commit

Permalink
Improve performance of number conversion in GelfEncoder #108
Browse files Browse the repository at this point in the history
  • Loading branch information
osiegmar committed Aug 24, 2024
1 parent 313c010 commit 1d861cf
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/main/java/de/siegmar/logbackgelf/GelfEncoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -312,18 +312,35 @@ private void addField(final Map<String, Object> dst, final String fieldName, fin
}
}

@SuppressWarnings("checkstyle:ReturnCount")
private Object convertToNumberIfNeeded(final Object value) {
if (numbersAsString || !(value instanceof String)) {
return value;
}

// Simple check if the string could be a number to avoid the performance overhead of exception handling
final char[] ca = ((String) value).toCharArray();
for (char c : ca) {
if (!isBigDecimalChar(c)) {
return value;
}
}

try {
return new BigDecimal((String) value);
return new BigDecimal(ca, 0, ca.length);
} catch (final NumberFormatException e) {
return value;
}
}

@SuppressWarnings("checkstyle:BooleanExpressionComplexity")
private static boolean isBigDecimalChar(final char c) {
return c >= '0' && c <= '9'
|| c == '.'
|| c == '+' || c == '-'
|| c == 'E' || c == 'e';
}

@Override
public void start() {
if (originHost == null || originHost.isBlank()) {
Expand Down

0 comments on commit 1d861cf

Please sign in to comment.