Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double brace initialization - Advantage

Got to know that we can initialize a collection in java by using double brace initialization. And did some search on that and found that it is not advised to use it because of its performance issue.

private static final Set<String> VALID_CODES = new HashSet<String>() {{
    add("XZ13s");
    add("AB21/X");
    add("YYLEX");
    add("AR2D");
 }};

Just want to know, is there any positive side or advantage of DOUBLE BRACE INITIALIZATION??

like image 499
Raja Asthana Avatar asked Jan 31 '13 13:01

Raja Asthana


2 Answers

not advised to use it because of its performance issue.

I don't see any performance issue. Whenever you see someone say I did/didn't do something for performance reason you should expect to see detailed analysis comparing the alternatives explaining how one met the specific required performance and the other did not. If you don't see all this you might assume the author is just guessing.

EDIT: While I will concede each class takes a small amount of time to load, the running performance is exactly the same. I have demonstrated here https://stackoverflow.com/a/14627268/57695

I would use double brace notation if you believe it's simpler and clearer.

A disadvantage is that your are changing the type of the collection which can confuse functions where that is not expected. e.g. equals.

Note: As Lukas Eder points out, you want to be careful if you do this in a non-static context. The anonymous sub-class collection will implicitly have a reference to the outer instance and if it lives longer than the collection, this would be a memory leak. Have you ever thought of the possibility of a memory leak?

like image 171
Peter Lawrey Avatar answered Nov 08 '22 14:11

Peter Lawrey


There's no particular performance issue (beyond the cost of loading a class via the classloader - negligible)

The above does create an anonymous class and as such it contains an implicit this reference to the surrounding instance. That can cause some confusion for serialisation frameworks. e.g. you serialise the anonymous class you've created, and you suddenly find you're also trying to serialise the containing instance.

I would highlight that anonymous classes can be used a lot under the covers in different frameworks and indeed languages (Scala - I'm looking at you). I've never heard anyone suggest that Scala has issues with performance due to classloading. Initial startup may be fractionally slower, but bear in mind JVM startup, JIT warmup, any network access etc.

You might argue that your application footprint is bigger, due to more classes. I suspect (again) the effect is negligible (unless you construct a whole application out of anonymous classes!)

like image 3
Brian Agnew Avatar answered Nov 08 '22 14:11

Brian Agnew