Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think it is an artefact of how you are benchmarking the code.</p> <p>I have run the following benchmark using JVM <code>1.7.0_09</code> with <code>-XX:+AggressiveOpts -XX:CompileThreshold=1</code>:</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.Random; public class Main { static final int COUNT = 1000000; static int[] ints = new int[COUNT]; static Integer[] integers = new Integer[COUNT]; static void primitiveToObject() { List&lt;Integer&gt; objects = new ArrayList&lt;Integer&gt;(ints.length); for (int i = 0; i &lt; ints.length; i++) { int value = ints[i] + 1; objects.add(value); //boxing } } static void objectsToPrimitiveToObject() { List&lt;Integer&gt; result= new ArrayList&lt;Integer&gt;(integers.length); for (int i = 0; i &lt; integers.length; i++) { int value = integers[i] + 1; //unboxing result.add(value); //boxing } } public static void main(String[] args) { Random rand = new Random(); for (int i = 0; i &lt; COUNT; ++i) { int val = rand.nextInt(); ints[i] = val; integers[i] = val; } for (int i = 0; i &lt; 10; ++i) { long start_p = System.currentTimeMillis(); for (int j = 0; j &lt; 100; ++j) { primitiveToObject(); } long end_p = System.currentTimeMillis(); long start_o = System.currentTimeMillis(); for (int j = 0; j &lt; 100; ++j) { objectsToPrimitiveToObject(); } long end_o = System.currentTimeMillis(); System.out.printf("p2o:%d o2p2o:%d\n", end_p - start_p, end_o - start_o); } } } </code></pre> <p>The results were as follows:</p> <pre><code>p2o:2043 o2p2o:818 p2o:709 o2p2o:748 p2o:670 o2p2o:756 p2o:675 o2p2o:742 p2o:679 o2p2o:750 p2o:700 o2p2o:757 p2o:738 o2p2o:733 p2o:706 o2p2o:786 p2o:684 o2p2o:752 p2o:676 o2p2o:799 </code></pre> <p>As you can see, after the initial warm-up, <code>primitiveToObject()</code> is faster, as one might expect from a method that's doing less work.</p> <p>For completeness, I've also tested this using JDK 6, and observed similar results.</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. 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