8010849: (str) Optimize StringBuilder.append(null)
authormartin
Mon, 08 Apr 2013 16:37:35 -0700
changeset 16742 e6b0ac6581f1
parent 16741 36089fa1bbb5
child 16743 b0b34102bb4c
8010849: (str) Optimize StringBuilder.append(null) Summary: Append 4 chars instead of the string "null" Reviewed-by: mduigou, forax, jgish
jdk/src/share/classes/java/lang/AbstractStringBuilder.java
--- a/jdk/src/share/classes/java/lang/AbstractStringBuilder.java	Mon Apr 08 15:29:24 2013 -0400
+++ b/jdk/src/share/classes/java/lang/AbstractStringBuilder.java	Mon Apr 08 16:37:35 2013 -0700
@@ -415,7 +415,8 @@
      * @return  a reference to this object.
      */
     public AbstractStringBuilder append(String str) {
-        if (str == null) str = "null";
+        if (str == null)
+            return appendNull();
         int len = str.length();
         ensureCapacityInternal(count + len);
         str.getChars(0, len, value, count);
@@ -426,7 +427,7 @@
     // Documentation in subclasses because of synchro difference
     public AbstractStringBuilder append(StringBuffer sb) {
         if (sb == null)
-            return append("null");
+            return appendNull();
         int len = sb.length();
         ensureCapacityInternal(count + len);
         sb.getChars(0, len, value, count);
@@ -439,7 +440,7 @@
      */
     AbstractStringBuilder append(AbstractStringBuilder asb) {
         if (asb == null)
-            return append("null");
+            return appendNull();
         int len = asb.length();
         ensureCapacityInternal(count + len);
         asb.getChars(0, len, value, count);
@@ -451,7 +452,7 @@
     @Override
     public AbstractStringBuilder append(CharSequence s) {
         if (s == null)
-            s = "null";
+            return appendNull();
         if (s instanceof String)
             return this.append((String)s);
         if (s instanceof AbstractStringBuilder)
@@ -460,6 +461,18 @@
         return this.append(s, 0, s.length());
     }
 
+    private AbstractStringBuilder appendNull() {
+        int c = count;
+        ensureCapacityInternal(c + 4);
+        final char[] value = this.value;
+        value[c++] = 'n';
+        value[c++] = 'u';
+        value[c++] = 'l';
+        value[c++] = 'l';
+        count = c;
+        return this;
+    }
+
     /**
      * Appends a subsequence of the specified {@code CharSequence} to this
      * sequence.