O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required