Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Calling <code>barReadMethod.setAccessible(true);</code> turns off the security checks which can make it a bit faster. Even if it is accessible, it has to check otherwise.</p> <p>If I run use a getter method with and without accessible true.</p> <pre><code>class Main { static class A { private final Integer i; A(Integer i) { this.i = i; } public Integer getI() { return i; } } public static void main(String... args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { A[] as = new A[100000]; for (int i = 0; i &lt; as.length; i++) as[i] = new A(i); for (int i = 0; i &lt; 5; i++) { long time1 = timeSetAccessible(as); long time2 = timeNotSetAccessible(as); System.out.printf("With setAccessible true %.1f ns, Without setAccessible %.1f ns%n", (double) time1 / as.length, (double) time2 / as.length); } } static long dontOptimiseAvay = 0; private static long timeSetAccessible(A[] as) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Method getter = A.class.getDeclaredMethod("getI"); getter.setAccessible(true); dontOptimiseAvay = 0; long start = System.nanoTime(); for (A a : as) { dontOptimiseAvay += (Integer) getter.invoke(a); } return System.nanoTime() - start; } private static long timeNotSetAccessible(A[] as) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { Method getter = A.class.getDeclaredMethod("getI"); // getter.setAccessible(true); dontOptimiseAvay = 0; long start = System.nanoTime(); for (A a : as) { dontOptimiseAvay += (Integer) getter.invoke(a); } return System.nanoTime() - start; } } </code></pre> <p>prints</p> <pre><code>With setAccessible true 106.4 ns, Without setAccessible 126.9 ns With setAccessible true 5.4 ns, Without setAccessible 29.4 ns With setAccessible true 3.2 ns, Without setAccessible 9.9 ns With setAccessible true 3.1 ns, Without setAccessible 9.0 ns With setAccessible true 3.1 ns, Without setAccessible 8.9 ns </code></pre> <p>For a simple getter, using setAccessible(true) can be three times faster.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload