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

Add `@Pure` to mark constant result of method

Attach filesAttach ScreenshotVotersWatch issueWatchersCreate sub-taskLinkCloneUpdate Comment AuthorReplace String in CommentUpdate Comment VisibilityDelete Comments
    XMLWordPrintableJSON

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 4.0.0-alpha-3
    • Component/s: None
    • Labels:
      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

            • Assignee:
              daniel_sun Daniel Sun
              Reporter:
              daniel_sun Daniel Sun

              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

                  Issue deployment