Details
-
Improvement
-
Status: Closed
-
Major
-
Resolution: Fixed
-
None
-
None
-
None
Description
In order to fully leverage the power of GString caching(GROOVY-9637), it would be good to have an annotaton to mark constant result of toString.
Currently we could mark classes immutable, but it's too restricted for many cases. Currently we just cache literal of GString when its all values are immutable, but for more common cases, if the result of value's toString is constant, we could cache too. For example:
final class Test { @groovy.transform.KnownImmutable // actually the class is not immutable... private static final class Item { private int toStringInvocationCount = 0 @Override synchronized String toString() { toStringInvocationCount++ return "item" } } static void main(String[] args) { Item item = new Item() new StringBuilder().append("item: ${item}") System.out.println(item.toStringInvocationCount) // yield 1 } }
Better annotation:
final class Test { private static final class Item { private int toStringInvocationCount = 0 @Override @groovy.transform.Pure synchronized String toString() { toStringInvocationCount++ return "item" } } static void main(String[] args) { Item item = new Item() new StringBuilder().append("item: ${item}") System.out.println(item.toStringInvocationCount) // yield 1 } }