[#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 9a365b101e
commit a958e9b5d5
2 changed files with 29 additions and 9 deletions

View File

@ -33,6 +33,7 @@ public final class StringUtil {
public static final String EMPTY_STRING = "";
private static final String[] BYTE2HEX_PAD = new String[256];
private static final String[] BYTE2HEX_NOPAD = new String[256];
private static final char PACKAGE_SEPARATOR_CHAR = '.';
static {
// Determine the newline character of the current platform.
@ -305,16 +306,12 @@ public final class StringUtil {
* with anonymous classes.
*/
public static String simpleClassName(Class<?> clazz) {
if (clazz == null) {
return "null_class";
}
Package pkg = clazz.getPackage();
if (pkg != null) {
return clazz.getName().substring(pkg.getName().length() + 1);
} else {
return clazz.getName();
String className = ObjectUtil.checkNotNull(clazz, "clazz").getName();
final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (lastDotIdx > -1) {
return className.substring(lastDotIdx + 1);
}
return className;
}
private StringUtil() {

View File

@ -81,4 +81,27 @@ public class StringUtilTest {
public void substringAfterTest() {
assertEquals("bar:bar2", substringAfter("foo:bar:bar2", ':'));
}
@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 { }
}