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?
Take a look at the first note under Double Quoted String.
Double quoted strings are plain
java.lang.String
if there’s no interpolated expression, but aregroovy.lang.GString
instances if interpolation is present.
This is possible because the interpolation is detected lazily and therefore determined whether to refer it as a GString or String. For example try to assertions below:
assert 'sample'.class.simpleName == 'String'
assert "sample".class.simpleName == 'String'
assert "sample ${1 != 2}".class.simpleName == 'GStringImpl'
Second assertion above makes it clear that double quotes are String
by default until there is an interpolation (as in third assertion).
So, it does not matter if single or double quotes are used for as long as interpolation is not present. However, I personally do not think there should be any worry about performance benefits at the scale of using String
or GString
.
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 ", "" });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With