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 ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.