Showing posts with label ObjectPooling. Show all posts
Showing posts with label ObjectPooling. Show all posts

Wednesday, 25 February 2015

Object pooling with valueOf()

We have all wrapped primitive int with wrapper Integer objects.

The regular way to achieve this would be to write:

Integer ONE = new Integer (1);

This would instantiate a new object each time as evidenced by the presence of the new operator. This repeated instantiation is wasteful most of the time.

We can do a one time instantiation of the object and pool the same object to re-use it when it is deemed required later. This may be done with the valueOf method.

Integer ONE = Integer.valueOf(1);

This may be compared to String instantiation by two different techniques:

String happy = "happy"; (pooling)
String happy = new String ("happy"); (non-pooling)