Search code examples
javaperformancegroovyreflectionjvm-bytecode

Is it good option to use groovy objects rather than using java reflection


In java reflection, we generally try to get fields value at runtime by its attribute name. But considering performance impact its not recommended to use reflection.

But in this case can we use groovy objects which allows the retrieval of value by name of attribute

For example:

Person.groovy

Class Person { String name }

MainApp.java

Class MainApp { 
       public static void main(String[] args) { 
             Person p = new Person(); 
             p."name"="jonh";
       }
}

Will this have same performance as of reflection?


Solution

  • Many dynamic groovy features will use reflection or something similar causing less performance than statically compiled code would. In some cases Groovy code may even use internally thrown and caught exceptions. From Cédric Champeau's blog:

    [...] someone made a terrible design decision in Groovy. [...] the idea was to rely on exceptions to control the flow of resolution of properties. This means that when a property is missing, typically in a closure, an exception is thrown. When a method is not found, an exception is thrown. When a property is not found, an exception is thrown. That seemed to be a good idea, because in the end, you want to provide the user with an error, but in practice, this is catastrophic, because Groovy can capture those exceptions. [...] And that has a terrible impact on performance. [...] So, if you’re writing a plugin in Groovy, for the sake of performance, please add @CompileStatic.

    But by using Groovy you already accept this kind of performance impact in so many places that this question seems pointless. If you worry about this kind of micro-performance issues, Groovy is generally the wrong language.

    Note that by using @CompileStatic on all your classes, you can probably avoid this kind of performance issues for your own code (But then dynamic features will not compile / behave differently), but it could still be the case for any groovy SDK or groovy library class you depend on.

    Regarding field access

    In your example, if you use a constant String, the compiler might however optimize this to p.name.

    Whether it does or not may depend on the Groovy version (future versions may handle this differently than current ones).