From 25fc1191fdc62a43dede30c87edc5c3eb5d5cae7 Mon Sep 17 00:00:00 2001 From: franz1981 Date: Wed, 13 Mar 2024 15:40:39 -0400 Subject: [PATCH] Reduce allocations and batch appends on StringUtil::replaceNonAlphanumericByUnderscores --- .../config/common/utils/StringUtil.java | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/common/src/main/java/io/smallrye/config/common/utils/StringUtil.java b/common/src/main/java/io/smallrye/config/common/utils/StringUtil.java index 6faefd8f3..9c15f7594 100644 --- a/common/src/main/java/io/smallrye/config/common/utils/StringUtil.java +++ b/common/src/main/java/io/smallrye/config/common/utils/StringUtil.java @@ -94,21 +94,37 @@ public static boolean isAsciiLetterOrDigit(char c) { } public static String replaceNonAlphanumericByUnderscores(final String name) { - return replaceNonAlphanumericByUnderscores(name, new StringBuilder(name.length())); + return replaceNonAlphanumericByUnderscores(name, null); } - public static String replaceNonAlphanumericByUnderscores(final String name, final StringBuilder sb) { + public static String replaceNonAlphanumericByUnderscores(final String name, StringBuilder sb) { int length = name.length(); + int copyIndex = -1; for (int i = 0; i < length; i++) { char c = name.charAt(i); - if (isAsciiLetterOrDigit(c)) { - sb.append(c); - } else { + if (!isAsciiLetterOrDigit(c)) { + if (sb == null) { + sb = new StringBuilder(name.length()); + } + if (copyIndex != -1) { + sb.append(name, copyIndex, i); + copyIndex = -1; + } sb.append('_'); if (c == '"' && i + 1 == length) { sb.append('_'); } + } else { + if (copyIndex == -1) { + copyIndex = i; + } + } + } + if (copyIndex != -1) { + if (sb == null) { + return name; } + sb.append(name, copyIndex, length); } return sb.toString(); }