Faster rounding up to nearest power of two

XMLWordPrintable

    • Type: Enhancement
    • Resolution: Fixed
    • Priority: P4
    • 11
    • Affects Version/s: None
    • Component/s: core-libs
    • b15

        In java.util.HashMap the table size is calculated to be rounded up to a power of two:

            static final int tableSizeFor(int cap) {
                int n = cap - 1;
                n |= n >>> 1;
                n |= n >>> 2;
                n |= n >>> 4;
                n |= n >>> 8;
                n |= n >>> 16;
                return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
            }


        It could be done faster with use of Integer.numberOfLeadingZeros():

            static final int tableSizeFor(int cap) {
                int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
                return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
            }

        The same trick can be used in TimSort and ComparableTimSort.

              Assignee:
              Ivan Gerasimov
              Reporter:
              Ivan Gerasimov
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Created:
                Updated:
                Resolved: