Thursday, September 9, 2010

Groovy and Grails Strings

The other day on the freenode #grails channel schmolly159 pointed out a subtle diffrence in Groovy (and thus Grails) string handling. Let's see an example first.

log.warn("I am warning you!")
log.warn('I am warning you!')

In this example there are two log warning statements. They look very similar don't they? Look closely at the very minor difference. One is using double quotes for the string value and the other is using single quotes.

Now, the interesting part is actually how Groovy interprets the string. The double quoted string is actually a GString while the single quoted string is just a Java string.

"So what?", you might ask. In this specific example there is no technical reason to make Groovy use a GString. It's not using any of the features of the GString and thus we are just making Groovy work a bit harder to give us a Java string. Regardless of what "a bit harder" actually equates to (nanoseconds most likely), it all adds up.

In very large systems things like this add up over time. So be thoughtful about what kind of strings you are using. It could make a difference in the long-run.

2 comments:

  1. Your example is incorrect: the two log statements will perform identically. Groovy doesn't create a GString unless there is a $ or ${...} substitution inside the String. Double quotes do not automatically make a GString.

    Jochen "blackdrag" Theodorou goes into a lot of detail on the theoretical performance difference between Strings and GStrings in this discussion thread.

    ReplyDelete
  2. @Dana Thank you for the comment, and you are correct. The two will result in java.lang.String classes in the end. However, that's not the full story. The double quote string actually still needs to be evaluated to see if it needs to be a GString or String. The single quote which doesn't require this evaluation at all.

    ReplyDelete