Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8189230

JDK method:java.lang.Integer.numberOfLeadingZeros(int) can be optimized

XMLWordPrintable

    • b05

      A DESCRIPTION OF THE REQUEST :
      the origin code is :

      public static int numberOfLeadingZeros(int i) {
          // HD, Figure 5-6
          if (i == 0)
              return 32;
          int n = 1;
          if (i >>> 16 == 0) { n += 16; i <<= 16; }
          if (i >>> 24 == 0) { n += 8; i <<= 8; }
          if (i >>> 28 == 0) { n += 4; i <<= 4; }
          if (i >>> 30 == 0) { n += 2; i <<= 2; }
          n -= i >>> 31;
          return n;
      }
      I think it can be optimized ,should added following condition:

      if (i < 0)
              return 0;
      the fully optimized code is :

      public static int numberOfLeadingZeros(int i) {
          // HD, Figure 5-6
          if (i == 0)
              return 32;
          if (i < 0)
              return 0;
          int n = 1;
          if (i >>> 16 == 0) { n += 16; i <<= 16; }
          if (i >>> 24 == 0) { n += 8; i <<= 8; }
          if (i >>> 28 == 0) { n += 4; i <<= 4; }
          if (i >>> 30 == 0) { n += 2; i <<= 2; }
          n -= i >>> 31;
          return n;
      }

      JUSTIFICATION :
      In some condition, the intrinsic function may not called, the default java implementation will be run. then the original code will be slower than the optimized code.


            bpb Brian Burkhalter
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: