Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-9946

Add `@Pure` to mark constant result of method

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major
    • Resolution: Fixed
    • None
    • 4.0.0-alpha-3
    • 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
          }
      }
      

      Attachments

        Activity

          People

            daniel_sun Daniel Sun
            daniel_sun Daniel Sun
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Time Tracking

                Estimated:
                Original Estimate - Not Specified
                Not Specified
                Remaining:
                Remaining Estimate - 0h
                0h
                Logged:
                Time Spent - 1h 40m
                1h 40m