title: Java - performance of object pool vs new object instantiation
body: <p>I'm currently trying to build some code execution optimization for a contest, and was looking at the ObjectPool pattern to favor object reuse instead of new object instantiation.</p>
  
  <p>I've put together a <a href="https://github.com/sebastientromp/java-performance" rel="noreferrer">small project</a> (and the <a href="https://github.com/sebastientromp/java-performance/blob/master/src/test/java/ObjectPoolForLightweight.java" rel="noreferrer">only test class</a>) to investigate some of the things I see and don't understand.</p>
  
  <p>What I'm doing:</p>
  
  <ul>
  <li>compare the creation of very simple objects for 5 000 000 iterations using both the new() and Pool.get() operations</li>
  <li>play around three axes, running all tests with and without:
  
  <ul>
  <li>a "warmup" that runs the loop once before doing the measurements</li>
  <li>assigning the newly creating object to a local variable and using it for some computation</li>
  <li>using fixed vs random parameters as arguments</li>
  </ul></li>
  </ul>
  
  <p>The results I have are:
  <code>
  Figures are for new instantiation vs with object pool for 5 000 000 iterations
  without_warmup_without_new_object_use_with_random_parameters: 417 vs 457
  without_warmup_without_new_object_use_with_fixed_parameters: 11 vs 84
  without_warmup_with_new_object_use_with_random_parameters: 515 vs 493
  without_warmup_with_new_object_use_with_fixed_parameters: 64 vs 90
  with_warmup_without_new_object_use_with_random_parameters: 284 vs 419
  with_warmup_without_new_object_use_with_fixed_parameters: 8 vs 55
  with_warmup_with_new_object_use_with_random_parameters: 410 vs 397
  with_warmup_with_new_object_use_with_fixed_parameters: 69 vs 82
  </code></p>
  
  <p>What I notice from that:</p>
  
  <ul>
  <li>Using fixed parameters has a huge impact when instantiating a new object without reusing it. My guess was that the compiler was doing some kind of optimization and found that there was no side-effects and would remove the object instantiation altogether, but comparing the perfs with an empty loop shows that something still happens</li>
  <li>Using fixed parameters has a significant impact (though less pronounced) for the speed of new Object(), making it faster than the object pool version in some cases</li>
  <li>The object pool is faster in the "real life" scenarios (ie reuse the new objects and use somewhat random params), but not in most of them, which also hints at a compiler optimization.</li>
  </ul>
  
  <p>What I'm looking for here is to understand these results, and get pointers to docs / books that I could read to get a good knowledge of what happens behind the scenes in these cases.</p>
  
  <p>Thanks!</p>