I was reading through the SparseArray
class in android, and came across the following method:
public void removeAt(int index) {
if (mValues[index] != DELETED) {
mValues[index] = DELETED;
mGarbage = true;
}
}
Clearly this could as well has been written:
public void removeAt(int index) { Or public void removeAt(int index) {
if (mValues[index] != DELETED) { mValues[index] = DELETED;
mValues[index] = DELETED; mGarbage = true;
if (!mGarbage) }
mGarbage = true;
}
}
It would seem the android developers believed the array lookup mValues[index]
was faster than an array write, but the variable lookup wasn't faster than a variable write.
Is this really true? Does it depend on the VM, or is it general knowledge in compiled languages too?
Certainly the right-hand side version is not equivalent - because then mGarbage
is set to true whether or not the value has changed.
The left-hand side is equivalent to the original, but it's pointless.
Basically I think you've missed the side-effect of checking whether or not the existing value was allows DELETED: it allows mGarbage
to be set to true only if the method has actually had an effect. That has nothing to do with the performance of reading from the array.