The generation of a Fibonacci sequence can be carried on in several ways:
- using the
generate()
method- leaning on an external class to keep the state and perform the computation (method
fibonacciGG()
) - using a lambda with an external class just to keep the state (method
fibonacciGLP()
) - using a lambda storing the state into an external array (method
fibonacciGLa()
)
- leaning on an external class to keep the state and perform the computation (method
- using the
iterate()
method- using a lambda with an external class to keep the state (method
fibonacciILP()
) - using a lambda with an array to keep the state (method
fibonacciILa()
) - using a lambda with an array to keep the state that is re-created at each iteration (method
fibonacciILan()
)
- using a lambda with an external class to keep the state (method
The four implementations are shown in file FibonacciStream.java in the corresponding methods.
The time performance of the five alternatives above are reported in the following table and illustrated in the diagram.
Solution | Method | Time | Throughput |
---|---|---|---|
generate(Generator class) | fibonacciGG() |
94.5 | 106 |
generate(lambda, array) | fibonacciGLP() |
98.5 | 102 |
generate(lambda, Pair) | fibonacciGLa() |
93.5 | 107 |
iterate(lambda, new array) | fibonacciILan() |
70.0 | 143 |
iterate(lambda, array) | fibonacciILP() |
35.0 | 286 |
iterate(lambda, Pair) | fibonacciILa() |
31.0 | 323 |
The performance are based on CPU times collected on a Mac with 2.3 GHz Intel Core i7.
The time measure is the time required to generate a 10M numbers sequence.
The throughput is expressed in Million numbers generated per second.
The two best iterate()
solutions outperfom the generate()
based solutions by almost three times.
In both cases we observe that the array variants are performing slightly worsed than the ones using an external class. This is likely due to the additional checks performed when accessing an array.
The new array version of the iterate()
deserves some additional consideration.
It is the solution typically suggested in several places (several stackoverflow answers) as it is the most compact and possibly elegant.
Unfortunately it creates a new object every iteration, this solution is inefficient both from a time and memory occupation perspectives.