From a958e9b5d5d9d03b5c85a602c061d44ea25d7a52 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Sat, 18 Apr 2015 21:34:01 +0200 Subject: [PATCH] [#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. --- .../io/netty/util/internal/StringUtil.java | 15 +++++------- .../netty/util/internal/StringUtilTest.java | 23 +++++++++++++++++++ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/common/src/main/java/io/netty/util/internal/StringUtil.java b/common/src/main/java/io/netty/util/internal/StringUtil.java index b1121471d7..6940b24152 100644 --- a/common/src/main/java/io/netty/util/internal/StringUtil.java +++ b/common/src/main/java/io/netty/util/internal/StringUtil.java @@ -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() { diff --git a/common/src/test/java/io/netty/util/internal/StringUtilTest.java b/common/src/test/java/io/netty/util/internal/StringUtilTest.java index 036f5b1c29..7e15652ac8 100644 --- a/common/src/test/java/io/netty/util/internal/StringUtilTest.java +++ b/common/src/test/java/io/netty/util/internal/StringUtilTest.java @@ -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 { } }