JDK-7192942 : (coll) Inefficient calculation of power of two in HashMap
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 8
  • Priority: P4
  • Status: Closed
  • Resolution: Fixed
  • OS: generic
  • CPU: generic
  • Submitted: 2012-08-21
  • Updated: 2014-02-12
  • Resolved: 2013-08-01
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 7 JDK 8
7u60Fixed 8 b103Fixed
Description
This is a SUNBUG for 100189: https://bugs.openjdk.java.net/show_bug.cgi?id=100189

Constructor does this:

public HashMap(int initialCapacity, float loadFactor) {
  ...
  int capacity = 1;
  while (capacity < initialCapacity)
      capacity <<= 1;
  ...
}

It is magnitude+ faster to do this:

static final double LOG2 = Math.log(2.0);
public HashMap(int initialCapacity, float loadFactor) {
  ...
  int capacity = 1 << ((int)Math.ceil(Math.log(initialCapacity)/LOG2 ));
  ...
}


Given the error checking in the head of the constructor, this code should just
plug-in.

Comments
The issue was already fixed in jdk8 with A function roundUpToPowerOf2() was introduced that does the calculation faster than in a loop. However this function can also be optimized a bit.
30-07-2013