JDK-8060485 : (str) contentEquals checks the String contents twice on mismatch
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Priority: P4
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2014-10-14
  • Updated: 2015-06-04
  • Resolved: 2014-10-15
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 8 JDK 9
8u40Fixed 9 b36Fixed
Description
If you look at the String.contentEquals code, you will see:

    public boolean contentEquals(CharSequence cs) {
        ....
        // Argument is a String
        if (cs.equals(this))
            return true;
        // Argument is a generic CharSequence
        char v1[] = value;
        int n = v1.length;
        if (n != cs.length()) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            if (v1[i] != cs.charAt(i)) {
                return false;
            }
        }

That is, if we pass a String in, and we mismatch, we do the per-char test as the fallback, which is guaranteed to "false" again.
Comments
Updated patch: http://cr.openjdk.java.net/~shade/8060485/webrev.01/
14-10-2014

Running the targeted benchmark: http://cr.openjdk.java.net/~shade/8060485/StringContentEquals.java http://cr.openjdk.java.net/~shade/8060485/benchmarks.jar Yields the dramatic improvement: http://cr.openjdk.java.net/~shade/8060485/perf.txt
14-10-2014

Patch: http://cr.openjdk.java.net/~shade/8060485/webrev.00/
14-10-2014