6639443: Character.toCodePoint and Character.toSurrogates can be optimized
authormartin
Fri, 24 Jul 2009 18:16:14 -0700
changeset 3323 29b6893c6188
parent 3322 82096b9a8dd3
child 3324 02cc89024ea2
6639443: Character.toCodePoint and Character.toSurrogates can be optimized Summary: rearranging code saves 5 bytes of bytecode Reviewed-by: sherman
jdk/src/share/classes/java/lang/Character.java
--- a/jdk/src/share/classes/java/lang/Character.java	Thu Jul 23 12:36:52 2009 -0700
+++ b/jdk/src/share/classes/java/lang/Character.java	Fri Jul 24 18:16:14 2009 -0700
@@ -2784,8 +2784,13 @@
      * @since  1.5
      */
     public static int toCodePoint(char high, char low) {
-        return ((high - MIN_HIGH_SURROGATE) << 10)
-            + (low - MIN_LOW_SURROGATE) + MIN_SUPPLEMENTARY_CODE_POINT;
+        // Optimized form of:
+        // return ((high - MIN_HIGH_SURROGATE) << 10)
+        //         + (low - MIN_LOW_SURROGATE)
+        //         + MIN_SUPPLEMENTARY_CODE_POINT;
+        return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT
+                                       - (MIN_HIGH_SURROGATE << 10)
+                                       - MIN_LOW_SURROGATE);
     }
 
     /**
@@ -3071,9 +3076,10 @@
     }
 
     static void toSurrogates(int codePoint, char[] dst, int index) {
-        int offset = codePoint - MIN_SUPPLEMENTARY_CODE_POINT;
-        dst[index+1] = (char)((offset & 0x3ff) + MIN_LOW_SURROGATE);
-        dst[index] = (char)((offset >>> 10) + MIN_HIGH_SURROGATE);
+        // We write elements "backwards" to guarantee all-or-nothing
+        dst[index+1] = (char)((codePoint & 0x3ff) + MIN_LOW_SURROGATE);
+        dst[index] = (char)((codePoint >>> 10)
+            + (MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)));
     }
 
     /**