In the "95% of performance is about clean representative models" talk by Martin Thompson, between 17 and 21 minute, such code is presented:
public class Queue
{
private final Object[] buffer;
private final int capacity;
// Rest of the code
}
In 20:16 he says:
You can get much better performance, so leaving things like
capacity
in there is the right thing to do.
I tried to come up with a code example in which capacity
will be much faster than buffer.length
, but I failed.
Martin is saying that problems arise in two scenerios:
- In a concurrent world. But,
length
field is alsofinal
, JLS 10.7. So, I don't see how this could be a problem. - When a cache misses. I tried calling
capacity
vsbuffer.length
one million times (with queue having one million of elements), but there was no significant difference. I used JMH for benchmarking.
Could you please provide a code example, which demonstrates a case in which capacity
is superior to buffer.length
in terms of performance?
The more common case (frequently spotted in the real code), the better.
Please note, that I'm totally taking away the aspect of aesthetics, clean code, potential for code re-factoring etc. I'm asking only about the performance.