As I was looking at some code today that used FP concepts with Guava (Google
Collections), I saw the same pattern I see over and over in such Java code that
strives to be expressive in a functional manner: a function is required as a
parameter for some operation and it so happens that the code that sends that
function along instantiates the Guava Function object (or something similar,
like Comparator) there and then. The look of the code is as close to what we
can expect to see in a "true" functional language with current Java
capabilities, but more often than not, the purpose of including the guts of the
function right there is to bundle the function definition with its logical
context, not because we really need to instantiate the object in that place.
In
fact, typically, the anonymous inner class expressing said function always
produces identical instances. Here's a hypothetical example. Let's assume the
following gets called a lot throughout the uptime of the program:
final List<String> lowerCaseList = ...;
final List<String> upperCaseList = Lists.transform(lowerCaseList, new
Function<String, String>() {
public String apply(String s) { return s.toUpperCase(); }
});
This is quite readable, but in theory, the following would be more efficient:
final List<String> lowerCaseList = "...";
final List<String> upperCaseList = Lists.transform(lowerCaseList,
toUpperFunction);
where toUpperFunction is defined elsewhere, ensuring a more appropriate
lifespan
to the instance. Is there a JVM optimization that developers can reasonably
rely on, that would effectively promote this particular apply(String)
implementation to a "static" level, so that no instance memory would need to be
allocated and reclaimed, and no constructor would need to be called? And if
not, is this on the order of magnitude, where it's generally not a concern in
performance-sensitive scenarios?
Alexey
http://azinger.blogspot.com
http://bsheet.sourceforge.net
http://wcollage.sourceforge.net
--
You received this message because you are subscribed to the Google Groups "The
Java Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/javaposse?hl=en.