Skip to content

Instantly share code, notes, and snippets.

@runewake2
Created April 11, 2018 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runewake2/2d63de01f53619d2d5b976043dc12420 to your computer and use it in GitHub Desktop.
Save runewake2/2d63de01f53619d2d5b976043dc12420 to your computer and use it in GitHub Desktop.
An example of Groovy's `@Memoized` feature for automatically caching function results. From the video at World of Zero: https://youtu.be/90YDpzoeGEk
package com.worldofzero.example
import groovy.transform.Memoized
import java.util.concurrent.TimeUnit
/**
* An example use of Memoizing in Groovy
* World of Zero {@link youtube.com/worldofzerodevelopment}
*/
class Application {
static void main(String... args) {
int iterations = 20
long startTime = System.nanoTime()
for(int i = 0; i < iterations; ++i) {
System.out.println(fib(30))
}
long endTime = System.nanoTime()
long differenceTime = TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS)
System.out.println("Time taken $differenceTime ms")
}
@Memoized
static int fib(int n) {
switch(n) {
case 0:
return 0
case 1:
return 1
default:
if (n < 0) {
return 0
} else {
return fib(n - 1) + fib(n - 2)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment