title: Java Lambda performance vs declared Suppliers/Functions
body: <p>I am starting to learn how to develop with <code>Optional</code> in java8. It might be it is somwehere documented, but I have been using google with no accurate result.</p>
  
  <p>I have different possible implementations for the <code>orElseGet</code> method, and I am not sure if java makes a better memory handling in some case, or if its pretty much the same.</p>
  
  <p>Lets say I have a method in a class with an <code>Optional</code> defined:</p>
  
  <pre><code>class myClass {
  
    final static private Supplier&lt;Object&gt; MY_SUPPLIER = () -&gt; new Object();
  
    private void myMethod1 () {
      Optional&lt;Object&gt; x; // somehow Initialized
      Object y = x.orElseGet(() -&gt; new Object());
    }
  
    private void myMethod2 () {
      Optional&lt;Object&gt; x; // somehow Initialized
      Object y = x.orElseGet(MY_SUPPLIER);
    }
  }
  </code></pre>
  
  <p>From my humble point of view, this second should have better memory management in  java, since it's only declared once the <code>Supplier</code>, and it is always used the same.</p>
  
  <p>1) is this true?</p>
  
  <p>Now, let's go further, and imagine we need to supply different object depending on parameters.</p>
  
  <pre><code>class myClass2 {
  
    final static private Function&lt;String, Supplier&lt;AnyCustomClass&gt;&gt; MY_SUPPLIER_PROVIDER = (p) -&gt; () -&gt; new AnyCustomClass(p);
  
    private void myMethod1 (String arg) {
      Optional&lt;AnyCustomClass&gt; x; // somehow Initialized
      AnyCustomClass y = x.orElseGet(() -&gt; new AnyCustomClass(arg));
    }
  
    private void myMethod2 (String arg) {
      Optional&lt;AnyCustomClass&gt; x; // somehow Initialized
      AnyCustomClass y = x.orElseGet(MY_SUPPLIER_PROVIDER.apply(arg));
    }
  }
  </code></pre>
  
  <p>In this case, depending on the argument, each time it returns different supplier.</p>
  
  <p>2) Does java have better memory management here also?</p>
  
  <p>3) Do they somehow get "cached" for arg taking same value?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>By watching <a href="https://stackoverflow.com/questions/27524445/does-a-lambda-expression-create-an-object-on-the-heap-every-time-its-executed">Does a lambda expression create an object on the heap every time it's executed?
  </a> I understand that my first class behaviour is answered. Since there are no local variables, it will create a singleton (at least oracle jvm)</p>
  
  <p>How ever, I do not feel like that answer provides accurate information to answer my 2) and 3)</p>