Good programming practices

Lazy evaluation in Java

August 11th, 2011

Invoking some methods you may not know if passes arguments will be ever used. In most cases it wouldn’t be a problem. But sometimes evaluating not necessary arguments may cause performance issues. In Java all arguments are evaluated before call of a method. However, there are some circumvent.

Let’s suppose that HeavyObject cannot be constructed in this method (e.g. constructor may not be accessible) but may not be required. Early evaluation lookslike this.

  1. class LazyEvaluation {
  2. void useHeavyObject(HeavyObject heavy) {
  3. if (isHeavyObjectRequired()) {
  4. heavy.useIt();
  5. }
  6. }
  7. public static void main(String args[]) {
  8. LazyEvaluation lazy = new LazyEvaluation();
  9. //early evaluation
  10. lazy.useHeavyObject(new HeavyObject());
  11. }
  12. }

First method of lazy evaluation use the conditional operator. The object will be constructed only if isHeavyObjectRequired will return true.
  1. //lazy evaluation
  2. lazy.useHeavyObject(lazy.isHeavyObjectRequired() ? new HeavyObject() : null);

The second way need a factory of the HeavyObject. It can be the same or separate class. You can also use static method instead.
  1. class HeavyObjectFactory {
  2. HeavyObject getInstance() {
  3. return new HeavyObject();
  4. }
  5. }
  6. class LazyEvaluation {
  7. void useHeavyObjectFactory(HeavyObjectFactory factory) {
  8. if (isHeavyObjectRequired()) {
  9. factory.getInstance().useIt();
  10. }
  11. }
  12. public static void main(String args[]) {
  13. LazyEvaluation lazy = new LazyEvaluation();
  14. //use factory for lazy evaluation
  15. lazy.useHeavyObjectFactory(new HeavyObjectFactory());
  16. }
  17. }

Leave a Response

You must be logged in to post a comment.