I wonder how variables marked as final are interpreted by Groovy (in 1.8.0, 1.8.1). I know that it makes sense in Java and it is possible to improve the performance and -- of course -- help to avoid stupid mistakes. I would like to learn if final may help the java compiler to optimize a program written in Groovy. I wonder if Groovy transformers preserve the final markings for variables.
相关问题
- Grails External Configuration. Can't access to
- HTML5 - Canvas - Optimization for large images
- Need help fixing an algorithm that approximates pi
- Can I override cast operator in Groovy?
- Use Groovy to Sort XML File
相关文章
- Optimization techniques for backtracking regex imp
- Using Spring Dynamic Languages Support from Groovy
- Logging Django SQL queries with DEBUG set to False
- Grails: How to make everything I create Upper Case
- Optimising this C (AVR) code
- Pointer dereferencing overhead vs branching / cond
- What's the best way to minify the ASP.NET gene
- JavaScript replace with callback - performance que
not yet. but it might in a future, so I still mark them if appropriate.
https://issues.apache.org/jira/browse/GROOVY-1628
As Justin has said, if the optimisations that the compiler performs for final variables are important to you, then you shouldn't be using Groovy.
However, if the performance of Groovy is good enough, then it is still useful to mark variables final for two reasons:
Protecting your class' invariants, i.e. making sure that a value cannot be changed after object construction. Java enforces this at compile-time, Groovy only enforces this at runtime, but this is better than silently allowing an immutable value to be changed
Documentation. Users of your class can easily see which values they are allowed to change
It doesn't appear that
groovyc
will inline final variables the way javac does. I created two test scripts, one using final and one not:javap -c
produced the same output for both classes:javac
optimized away theastore
/aload
:Without
final
:With
final
:All that said, if performance is paramount, Groovy is a poor choice to begin with. Inlining final variables won't save you from the overhead of using reflection for method calls.