Is method reference caching a good idea in Java 8?

Posted by gexicide on Stack Overflow See other posts from Stack Overflow or by gexicide
Published on 2014-06-01T19:51:19Z Indexed on 2014/06/01 21:28 UTC
Read the original article Hit count: 148

Filed under:
|
|
|

Consider I have code like the following:

class Foo {

   Y func(X x) {...} 

   void doSomethingWithAFunc(Function<X,Y> f){...}

   void hotFunction(){
        doSomethingWithAFunc(this::func);
   }

}

Consider that hotFunction is called very often. Would it then be advisable to cache this::func, maybe like this:

class Foo {
     Function<X,Y> f = this::func;
     ...
     void hotFunction(){
        doSomethingWithAFunc(f);
     }
}

As far as my understanding of java method references goes, the Virtual Machine creates an object of an anonymous class when a method reference is used. Thus, caching the reference would create that object only once while the first approach creates it on each function call. Is this correct?

Should method references that appear at hot positions in the code be cached or is the VM able to optimize this and make the caching superfluous? Is there a general best practice about this or is this highly VM-implemenation specific whether such caching is of any use?

© Stack Overflow or respective owner

Related posts about java

Related posts about caching