duke

Divide and conquer

Canonical string comparison

Compare each character from the begining of the string to the end of the string

    static boolean slowEquals(String s1, String s2) {
        if (s1.length() == s2.length()) {
            for (int i = 0; i < s1.length(); i++) {
                if (s1.codePointAt(i) != s2.codePointAt(i)) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }

Faster string comparison

Compare each character from the begining, and end of the string towards the center end of the string. The runtime will be the same for identical strings as a canonical method, but potentially faster where the strings differ nearer the end

    static boolean fasterEquals(String s1, String s2) {
        if (s1.length() == s2.length()) {
            int midpoint = s1.length() / 2;

            for (int i1 = 0, i2 = s2.length()-1; i1 < midpoint; i1++, i2--) {
                if ((s1.codePointAt(i1) != s2.codePointAt(i1)) ||
                        (s1.codePointAt(i2) != s2.codePointAt(i2))) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }

Loop inwards from the ends

            for (int i1 = 0, i2 = s2.length()-1; i1 < midpoint; i1++, i2--) {
                if ((s1.codePointAt(i1) != s2.codePointAt(i1)) ||
                        (s1.codePointAt(i2) != s2.codePointAt(i2))) {
                    return false;
                }
            }