Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GWT.create() always create a new object in browser memory?

Suppose I do:

VeryLargeObject o1 = GWT.create(VeryLargeObject.class();
VeryLargeObject o2 = GWT.create(VeryLargeObject.class();
...
VeryLargeObject o1000 = GWT.create(VeryLargeObject.class();

where VeryLargeObject is a GWT resource interface which extends com.google.gwt.i18n.client.Messages.

Will this code create 1000 new instances of the object in the browser? Or is GWT smart enough to detect that VeryLargeObject is immutable and re-use it's 1 instance every time?

EDIT: I found this in docs but the behaviour is still not clear to me:

Using GWT.create(class) to "instantiate" an interface that extends Messages returns an instance of an automatically generated subclass that is implemented using message templates selected based on locale.

like image 747
Babken Vardanyan Avatar asked Jul 20 '15 06:07

Babken Vardanyan


1 Answers

Yes, GWT.create() will return a new instance each time. But a good generator will make it so that this can be optimized away in compiled code.

One of the first things the GWT compiler does is to tighten types (rewrite the code to use the most specific class possible; in this case, all uses of your messages interface will be replaced with the generated implementation) and then make methods static (except when dynamic dispatch is required, i.e. polymorphism is actually used).
For an I18N Messages interface, because the generated class has no state and its constructor has no side-effect, that means the instances can be optimized out and only the static methods are kept in the code (when they're not later inlined).
More "complex" cases (e.g. client bundles, CSS resources) will actually use "static state", so once again the instances themselves can be optimized out and in the end it doesn't matter if you created 1000 instances or shared just one.

like image 131
Thomas Broyer Avatar answered Sep 26 '22 14:09

Thomas Broyer