Thursday, January 1, 2009

The speed difference between the different types of Strings in Groovy and Grails

For everybody who wondered why the hell you should use other strings than single quoted strings in Groovy and Grails:
It's faster!
A lot!
Really?

Update: I started a thread on the Groovy user mailinglist in regards to this topic and I got some great explanations on how the Strings/GStrings work and behave. Check it out on the list at nabble.

Why is this interesting?
bobbytek asked the other day in #groovy on freenode which strings one should use when doing "dsl stuff". Single quoted or double quoted?

After going a back and forth with him and after we have been talking about PHP double quoted/single quoted strings and their performance differences I wrote a small script to check out if the single quoted strings are faster in Groovy than the double quoted strings.


The test
So I simply had to try out which strings are REALLY faster. The script I came up with for this purpose forges some single quoted, double quoted, slashy, multi line single and multi line double quoted strings in some loops. The script includes three test. First a simple static string without any substitutions. Second a substitution inside the string with another 'static' string. And last a substitution with an always changing variable (the loop index)

I ran the script with Groovy (1.0 and 1.5.6) on the console and also in Grails (1.1beta2) on Jetty.
Guess what: The results were very different!

I don't think the actual execution time is the main importance here but much rather the differences between the single tests and string types.

I didn't test it with Grails on any other application server besides Jetty with the standard configuration that comes with Grails. If somebody wants to run the script on Tomcat etc - please do so and let me know what the results are there!

Here are the results (click images for larger display):






Conclusion
After running the test, I think I will stick to the double quoted Strings in Grails when defining my domains etc. - I think I always did that as I am more used to the " than the ' due to the standard usage of " in the German language...
I don't know why the double quoted strings are seeming to be faster (without using closures etc) than the single quoted ones and I honestly didn't expect these results. However, I hope someone out there can confirm that this is not only my computer taking on my personal preference for using "! Btw: The results for the script when running Groovy 1.0 show that it actually makes sense to upgrade! ;)

If you have anything to add or if you find any mistakes please (!) let me know. Thanks for reading anyways.

You can download the results as PDF
You can download the script as .groovy file
blog comments powered by Disqus