[#3652] Improve performance of StringUtil.simpleClassName()

Motivation:

static Package getPackage(Class<?> c) uses synchronized block internally.
Thanks to @jingene for the hint and initial report of the issue.

Modifications:

-Use simple lastIndexOf(...) and substring for a faster implementation

Result:

No more lock condition.
This commit is contained in:
Norman Maurer 2015-04-18 21:34:01 +02:00
parent ab925abc7d
commit a7d1dc362a
2 changed files with 28 additions and 9 deletions

View File

@ -42,6 +42,7 @@ public final class StringUtil {
* 5 - Extra allowance for anticipated escape characters that may be added. * 5 - Extra allowance for anticipated escape characters that may be added.
*/ */
private static final int CSV_NUMBER_ESCAPE_CHARACTERS = 2 + 5; private static final int CSV_NUMBER_ESCAPE_CHARACTERS = 2 + 5;
private static final char PACKAGE_SEPARATOR_CHAR = '.';
static { static {
// Determine the newline character of the current platform. // Determine the newline character of the current platform.
@ -314,16 +315,12 @@ public final class StringUtil {
* with anonymous classes. * with anonymous classes.
*/ */
public static String simpleClassName(Class<?> clazz) { public static String simpleClassName(Class<?> clazz) {
if (clazz == null) { String className = ObjectUtil.checkNotNull(clazz, "clazz").getName();
return "null_class"; final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
} if (lastDotIdx > -1) {
return className.substring(lastDotIdx + 1);
Package pkg = clazz.getPackage();
if (pkg != null) {
return clazz.getName().substring(pkg.getName().length() + 1);
} else {
return clazz.getName();
} }
return className;
} }
/** /**

View File

@ -277,4 +277,26 @@ public class StringUtilTest {
} }
} }
@Test
public void testSimpleClassName() throws Exception {
testSimpleClassName(String.class);
}
@Test
public void testSimpleInnerClassName() throws Exception {
testSimpleClassName(TestClass.class);
}
private static void testSimpleClassName(Class<?> clazz) throws Exception {
Package pkg = clazz.getPackage();
String name;
if (pkg != null) {
name = clazz.getName().substring(pkg.getName().length() + 1);
} else {
name = clazz.getName();
}
assertEquals(name, simpleClassName(clazz));
}
private static final class TestClass { }
} }