Java: Getter and setter faster than direct access?

Mr.Yeah picture Mr.Yeah · May 29, 2014 · Viewed 9.6k times · Source

I tested the performance of a Java ray tracer I'm writing on with VisualVM 1.3.7 on my Linux Netbook. I measured with the profiler.
For fun I tested if there's a difference between using getters and setters and accessing the fields directly. The getters and setters are standard code with no addition.

I didn't expected any differences. But the directly accessing code was slower.

Here's the sample I tested in Vector3D:

public float dot(Vector3D other) {
    return x * other.x + y * other.y + z * other.z;
}

Time: 1542 ms / 1,000,000 invocations

public float dot(Vector3D other) {
    return getX() * other.getX() + getY() * other.getY() + getZ() * other.getZ();
}

Time: 1453 ms / 1,000,000 invocations

I didn't test it in a micro-benchmark, but in the ray tracer. The way I tested the code:

  • I started the program with the first code and set it up. The ray tracer isn't running yet.
  • I started the profiler and waited a while after initialization was done.
  • I started a ray tracer.
  • When VisualVM showed enough invocations, I stopped the profiler and waited a bit.
  • I closed the ray tracer program.
  • I replaced the first code with the second and repeated the steps above after compiling.

I did at least run 20,000,000 invocations for both codes. I closed any program I didn't need. I set my CPU on performance, so my CPU clock was on max. all the time.
How is it possible that the second code is 6% faster?

Answer

Bohemian picture Bohemian · Jun 5, 2014

I did done some micro benchmarking with lots of JVM warm up and found the two approaches take the exact same amount of execution time.

This happens because the JIT compiler is in-lining the getter method with a direct access to the field thus making them identical bytecode.