Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When/why would I want to use Groovy's @CompileStatic?

Tags:

I've read this: http://docs.groovy-lang.org/latest/html/gapi/groovy/transform/CompileStatic.html, and this: Should I use Groovy's @CompileStatic if I'm also using Java 7, and understand there are certainly performance improvements to be had but is that it? I don't understand exactly what @CompileStatic does.

Are there certain classes on which adding @CompileStatic is a no-brainer? Where would I not want it?

like image 722
icfantv Avatar asked Apr 13 '15 15:04

icfantv


People also ask

What does CompileStatic do in groovy?

Annotation Type CompileStatic This will let the Groovy compiler use compile time checks in the style of Java then perform static compilation, thus bypassing the Groovy meta object protocol. When a class is annotated, all methods, properties, files, inner classes, etc. of the annotated class will be type checked.

Is Groovy statically typed?

Java is statically-typed, so it expects its variables to be declared before they can be assigned values. Groovy is dynamically-typed and determines its variables' data types based on their values, so this line is not required.


1 Answers

To cite my part of my answer to Should I use Groovy's @CompileStatic if I'm also using Java 7:

While faster than normal Groovy, it can compile only a subset of Groovy and behaves a bit different. Especially all the dynamic features are not available anymore.

All of the MOP will be bypassed. Builders won't work in general, some have extensions to the compiler to allow them passing though. Also methods are selected at compile time using static types, while Groovy normally uses the methods available at runtime and the runtime types. This can result in different methods being called.

Of course @CompileStatic also provides some security, since it is the tasks of a compiler to verify programs at runtime. But since static information is doomed to be incomplete, there can never be a 100% security.

So where is it a no-brainer... well... POGOs for example, since they don't usually contain all that much code. And of course for classes ported from Java to Groovy by copy&paste.

Where would I want it? Well, currently probably on Android, since there the code size has an impact and the static compiled code is more compact. Otherwise I personally am fine with not using @CompileStatic at all. This is more a matter of taste. In some cases there is a performance improvement for tight loops, but that requires you going and identifying by profiling your application first

like image 78
blackdrag Avatar answered Sep 17 '22 15:09

blackdrag