5

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.

Babken Vardanyan
  • 14,090
  • 13
  • 68
  • 87
  • 1
    You can print o1.toString(), o2.toString() etc. so you can check if the same value is printed. If yes, then they are they refer to the same object. – Alkis Kalogeris Jul 20 '15 at 06:59
  • 1
    @alkis Yes, in dev mode the hash code of new objects are different. But that's not a guarantee that that in production mode these objects don't references the same object underneath. – Babken Vardanyan Jul 20 '15 at 09:25

2 Answers2

4

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.

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
2

According to the GWT Javadoc the create() method is going to return a new instance, so I doubt it's the same object

http://www.gwtproject.org/javadoc/latest/com/google/gwt/core/client/GWT.html#create(java.lang.Class)

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – duffy356 Jul 20 '15 at 07:21
  • 3
    I did post "the essential parts of the answer" : "**Returns: the new instance**, which must be cast to the requested class". It's not a thick text –  Jul 20 '15 at 07:22