title: Java: Getter and setter faster than direct access?
body: <p>I tested the performance of a Java ray tracer I'm writing on with <a href="http://visualvm.java.net">VisualVM</a> 1.3.7 on my Linux Netbook. I measured with the profiler.<br>
  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.</p>
  
  <p>I didn't expected any differences. But the directly accessing code was slower.</p>
  
  <p>Here's the sample I tested in Vector3D:</p>
  
  <pre><code>public float dot(Vector3D other) {
      return x * other.x + y * other.y + z * other.z;
  }
  </code></pre>
  
  <p>Time: 1542 ms / 1,000,000 invocations</p>
  
  <pre><code>public float dot(Vector3D other) {
      return getX() * other.getX() + getY() * other.getY() + getZ() * other.getZ();
  }
  </code></pre>
  
  <p>Time: 1453 ms / 1,000,000 invocations</p>
  
  <p>I didn't test it in a micro-benchmark, but in the ray tracer. The way I tested the code:</p>
  
  <ul>
  <li>I started the program with the first code and set it up. The ray tracer isn't running yet.</li>
  <li>I started the profiler and waited a while after initialization was done.</li>
  <li>I started a ray tracer.</li>
  <li>When VisualVM showed enough invocations, I stopped the profiler and waited a bit.</li>
  <li>I closed the ray tracer program.</li>
  <li>I replaced the first code with the second and repeated the steps above after compiling.</li>
  </ul>
  
  <p>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.<br>
  How is it possible that the second code is 6% faster?</p>