Over a million developers have joined DZone.
Platinum Partner

Groovy Goodness: More Efficient Tail Recursion With TailRecursive Annotation

The Performance Zone is presented by AppDynamics. Scalability and better performance are constant concerns for the developer and operations manager. Try AppDynamics' fully-featured performance tool for Java, .NET, PHP, & Node.js.

Since 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

long sizeOfList(list, counter = 0) {
    if (list.size() == 0) {
    } else {
       sizeOfList(list.tail(), counter + 1) 

// Without @TailRecursive a StackOverFlowError
// is thrown.
assert sizeOfList(1..10000) == 10000

Code written with Groovy 2.3.

The Performance Zone is presented by AppDynamics. AppDynamics is a leader in the APM space with massive cost reductions for users.


Published at DZone with permission of Hubert Klein Ikkink , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}