I had a remark about a piece of code in the style of:
Iterable upperCaseNames = Iterables.transform(
lowerCaseNames, new Function
Fun fact about Sun/Oracle JVM optimizations, if you instantiate an object that isn't passed outside of the thread, the JVM will create the object on the stack instead of the heap.
Usually, stack allocation is associated with languages that expose the memory model, like C++. You don't have to delete
stack variables in C++ because they're automatically deallocated when the scope is exited. This is contrary to heap allocation, which requires you to delete the pointer when you're done with it.
In the Sun/Oracle JVM, the bytecode is analyzed to decide if an object can "escape" the thread. There are three levels of escape:
This basically is analogous to the questions, 1) do I pass/return it, and 2) do I associate it with something attached to a GC root? In your particular case, the anonymous object will be tagged as "no local escape" and will be allocated to the stack, then cleaned up by simply popping the stack on each iteration of the Sorry, I wasn't paying much attention when I wrote up my answer. It's actually local escape, which only means that any locks (read: use of for
loop, so cleaning it up will be super-fast.synchronized
) on the object will be optimized away. (Why synchronize on something that won't ever be used in another thread?) This is different from "no escape", which will do allocation on the stack. It's important to note that this "allocation" isn't the same as heap allocation. What it really does is allocates space on the stack for all the variables inside the non-escaping object. If you have 3 fields, int
, String
, and MyObject
inside the no-escape object, then three stack variables will be allocated: an int
, a String
reference, and a MyObject
reference. The object allocation is then optimized away and constructors/methods will run using the local stack variables instead of heap variables.
That being said, it sounds like premature optimization to me. Unless the code is later proven to be slow and is causing performance problems, you shouldn't do anything to reduce its readability. To me, this code is pretty readable, I'd leave it alone. This is totally subjective, of course, but "performance" is not a good reason to change code unless it has something to do with its algorithmic running time. Usually, premature optimization is an indicator of an intermediate-level coder. "Experts" (if there is such a thing) just write code that's easier to maintain.