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

Reduce allocations and batch appends on StringUtil::replaceNonAlphanumericByUnderscores #1133

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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 @@ -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();
}
Expand Down