Why does Java's String.equals() method use two counting variables?

Viewed 1088

I was just looking through the implementation of Java's String class and the following struck me as odd:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {               // Here n is being decremented...
                if (v1[i] != v2[i])
                    return false;
                i++;                         // while i is being incremented
            }
            return true;
        }
    }
    return false;
}

This could easily be implemented with just one counting variable while n would be effectively final, like this:

while (i != n) {
    if (v1[i] != v2[i])
        return false;
    i++;
}

Theres also this, which gets rid of the i entirely:

while (n-- != 0) {
    if (v1[n] != v2[n])
        return false;
}

Does it have to do with comparison to 0 being (a miniscule bit) cheaper than to another variable or is there any other particular reason as to why it is implemented that way?

3 Answers
Related