-
Notifications
You must be signed in to change notification settings - Fork 18
Memoize methods of Java objects
aburkov edited this page Jun 27, 2015
·
1 revision
With xpresso you can easily memoize Java methods.
As a quick example, let xerox be a Function object whose method apply copies the string "hello" the given number count of times:
Function<Integer, String> xerox = new Function<Integer, String>() {
public String apply(Integer count) {
return x.String("hello").times(count);
}
};
It's a long to execute function for large values of count.
In order to avoid the long computation for the same value of count, we first create a cached version of xerox using x.memo:
Function<Integer,String> cachedXerox = x.memo(xerox);
The first call of the function. The computation takes a very long time:
x.timer.start();
String copies = cachedXerox.apply(5000000);
x.print(x.timer.stop());
Console: 18.898s
The second call with the same value of count, the result is instantaneous:
x.timer.start();
String moreCopies = cachedXerox.apply(5000000);
x.print(x.timer.stop());
Console: 0.0s
x.memo can be used to cache methods of object of any Java type, not only Function. Notice the usage of the standard x.timer: no additional timer object needs to be created.