Memoization and the flyweight pattern
Memoization is caching of oft-repeated computation results. This is a way to avoid recalculating the result again. Flyweight is a design pattern that uses memoization. A flyweight is an object that minimizes memory use by sharing. A very good example of a flyweight is Java's Integer.valueOf(int)
method.
Java supports autoboxing of primitives to corresponding wrapper types. We should always prefer. Let's have a look at the following snippet:
int someInt = ...; Integer someInteger = someInt;
instead of the following:
new Integer(someInt);
If we happen to auto-box (int
→ Integer) values in the range of 128 to 127, the valueOf()
method allows us to reuse the Integer
object. As integer instances are immutable, we can rest easy about sharing the same integer instance across the application.
The following JUnit test case shows the memoization:
@Test public void test() { Integer a1 = Integer.valueOf(12); Integer a2 = Integer.valueOf...