title: Helping the JVM with stack allocation by using separate objects
body: <p>I have a bottleneck method which attempts to add points (as x-y pairs) to a HashSet.  The common case is that the set already contains the point in which case nothing happens.  Should I use a separate point for adding from the one I use for checking if the set already contains it?  It seems this would allow the JVM to allocate the checking-point on stack.  Thus in the common case, this will require no heap allocation.</p>
  
  <p>Ex.  I'm considering changing</p>
  
  <pre><code>HashSet&lt;Point&gt; set;
  
  public void addPoint(int x, int y) {
      if(set.add(new Point(x,y))) {
          //Do some stuff
      }
  }
  </code></pre>
  
  <p>to</p>
  
  <pre><code>HashSet&lt;Point&gt; set;
  public void addPoint(int x, int y){
      if(!set.contains(new Point(x,y))) {
          set.add(new Point(x,y));
          //Do some stuff
      }
  }
  </code></pre>
  
  <p>Is there a profiler which will tell me whether objects are allocated on heap or stack?</p>
  
  <p>EDIT:  To clarify why I think the second might be faster, in the first case the object may or may not be added to the collection, so it's not non-escaping and cannot be optimized.  In the second case, the first object allocated is clearly non-escaping so it can be optimized by the JVM and put on stack.  The second allocation only occurs in the rare case where it's not already contained.</p>