I tend to use (or even overuse) double braces object intialization in GWT. For me it looks more readable and more declarative.
new FastMap<Object>(){{
put("Value", 12);
put("Unit", "Kg");
}};
Before today I was not aware that this syntax is not just instantiate object but also create AnonymousInnerClass for it. Now I am concerned how GWT deal with them.
I have thousands of such initializations in my app.
Disadvantages of Using Double Braces It creates an extra class every time we use it. Doesn't support the use of the “diamond operator” – a feature introduced in Java 7. Doesn't work if the class we are trying to extend is marked final. Holds a hidden reference to the enclosing instance, which may cause memory leaks.
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces).
My findings. Test code. I am creating single list with 4 maps with 21 item each. I am measuring size of all generated JavaScript files. Results:
Empty (just empty code to make sure that GWT support code rendered):
new
= 167Code without double braces:
new
= 171And same code with double braces:
new
= 177I think results are pretty self-explanatory.
This is standard Java and is independent of GWT. It is dealt with comprehensively in Efficiency of Java “Double Brace Initialization”?.
The biggest problem I have with this syntax is that is doesn't deliver an instance of FastMap
, but rather of an anonymous subclass of that. That object doesn't compare as equal to an equivalent instance of FastMap
with the data set up in the traditional way. It is also likely to have other gotchas that aren't obvious and are less that straightforward to debug.
The thread here says this
Watch out - double-brace initialization is cool looking, but it's orders of magnitude slower than regular initialization as it must generate an anonymous class.
Also, the generated class is put into the permgen space, which is not garbage collected. The permgen is pretty small by default - and if you fill it up, your system is hosed.
I use them all the time in unit tests, but never in production code.
As far as readability is concerned: I would change it to something like this to make it easy to read:
new FastMap<Object>()
{{
put("Value", 12);
put("Unit", "Kg");
}};
You however might want to read this answer to find out more about performance related issues.
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