Groovy Goodness: More Efficient Tail Recursion With TailRecursive Annotation
Join the DZone community and get the full member experience.
Join For FreeSince Groovy 1.8 we can use the trampoline
method for a closure to get better recursive behavior for tail recursion. All closure invocations are then invoked sequentially instead of stacked, so there is no StackOverFlowError
. As from Groovy 2.3 we can use this for recursive methods as well with the @TailRecursive
AST transformation. If we apply the annotation to our method with tail recursion the method invocations will be sequential and not stacked, like with the closure's trampoline
method.
import groovy.transform.TailRecursive @TailRecursive long sizeOfList(list, counter = 0) { if (list.size() == 0) { counter } else { sizeOfList(list.tail(), counter + 1) } } // Without @TailRecursive a StackOverFlowError // is thrown. assert sizeOfList(1..10000) == 10000
Code written with Groovy 2.3.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Competing Consumers With Spring Boot and Hazelcast
-
MLOps: Definition, Importance, and Implementation
-
Mastering Time Series Analysis: Techniques, Models, and Strategies
-
Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs
Comments