I had a look at the source code of the String.hashcode() method. This was the implementation in 6-b14
, which has been changed already.
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
My question is about this line:
int len = count;
Where count
is a global variable representing the amount of characters of the String.
Why is a local variable len
used here for the loop condition and not the global variable itself? Because there is no manipulating of the variable, only reading. Is it just good practice to use a local variable if a global field is used for reading from or writing to it? If the answer is yes why for reading too?