Andy Malakov software blog

Tuesday, August 5, 2008

Direct field vs. Method access times

In my opinion there is no justification for using 'friendly' direct access to mutable class fields rather than getters and setters properties. I heard the following two arguments:

1. It makes performance-critical code run faster.



False. There is no benefit of direct access in frequently executed code. Chart below compares access time of direct field access to getters and setters.



As you can see, after 20,000 calls there is no difference in performance. This threshold is controlled by -XX:CompileThreshold JVM argument. Core of the test:


final long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
if ((mv.getField() & 0x101) != 0)
mv.setField(mv.getField()+1);
else
mv.setField(mv.getField()+2);
}
final long t1 = System.nanoTime();
for (int i = 0; i < n; i++) {
if ((fv.field & 0x101) != 0)
fv.field = (fv.field+1);
else
fv.field = (fv.field+2);
}
final long t2 = System.nanoTime();



2. Direct field access reduces bureaucracy.


Read: I am too lazy to write getters and setters. Well, Eclipse and Netbeans have "Encapsulate Field" and "Generate getters and Setters" commands. And BTW, what none of free IDEs have is "Find where modified" search for class fields.

Having said that, I have no problems with public final fields :-)