I recently ran across the following snippet in an existing codebase I'm working on and added the comment you see there. I know this particular piece of code can be rewritten to be cleaner, but I just wonder if my analysis is correct.
Will java create a new class declaration and store it in perm gen space for every call of this method, or will it know to reuse an existing declaration?
protected List<Object> extractParams(HibernateObjectColumn column, String stringVal) {
// FIXME: could be creating a *lot* of anonymous classes which wastes perm-gen space right?
return new ArrayList<Object>() {
{
add("");
}
};
}
The other answers are correct.
However:
If that pattern is repeated a number of times in your code, then you will end up with an equal number of inner classes. If you use the pattern hundreds / thousands of times, the increased code footprint / permgen usage could be significant.
What you are doing in this particular example could be expressed more simply as
protected List<Object> extractParams(HibernateObjectColumn column,
String stringVal) {
return Collections.singletonList("");
}
For cases where you have to populate the list with multiple values, a solution involving a static helper method is probably simpler.
The class will only be compiled once (at compile time). The compiler extracts a class (named something like MyOuterClass$1
) and uses it. It will create multiple instances, of course, but they will all be of the same class. You can see that when you compile the .java
file and look at the .class
files generated - there will be one for the inner anonymous class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With