Search code examples
performancegroovygstring

In Grails and Groovy, do Strings (in single quotes) outperform GStrings?


Since in Grails and Groovy, single-quoted Strings are different class from GStrings (double quoted Strings allowing ${variable} value injection), is it more efficient to use single quotes, except when ${variables} are being used? I am guessing that the presence of the double quotes would require parsing of the String that an ordinary single-quoted String would not require. Therefore I would expect a very slight performance hit from the extra time looking for the presence of the ${}.

So, it would seem that it would be beneficial in general to have a convention to encourage the use single quotes, unless there is a specific advantage to using the double quotes. Am I off base?


Solution

  • is it more efficient to use single quotes, except when ${variables} are being used?

    No. For the scenario where no ${variables} are used, they perform exactly the same. If there are no ${variables} in a double quoted String then the system does not create a GString. It creates a standard java.lang.String.

    EDIT To Address A Separate Question Posted In A Comment Below:

    It happens at compile time. The code below:

    void someMethod(String a) {
        def s1 = "some string"
        def s2 = "some string with arg ${a}"
    }
    @groovy.transform.CompileStatic
    void someOtherMethod(String a) {
        def s1 = "some string"
        def s2 = "some string with arg ${a}"
    }
    

    Compiles to this:

    public void someMethod(String a)
    {
        CallSite[] arrayOfCallSite = $getCallSiteArray();
        Object s1 = "some string";
        Object s2 = new GStringImpl(new Object[] { a }, new String[] { "some string with arg ", "" });
    }
    
    public void someOtherMethod(String a)
    {
        String s1 = "some string";
        GString s2 = new GStringImpl(new Object[] { a }, new String[] { "some string with arg ", "" });
    }