O'Reilly logo

Java 11 Cookbook by Mohamed Sanaulla, Nick Samoylov

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

How to do it...

  1. Pay attention to the object created inside the loop. 

This recommendation is pretty obvious. Creating and discarding many objects in quick succession may consume too much memory before the garbage collector catches up with reusing the space. Consider reusing objects instead of creating a new one every time. Here is an example:

class Calculator {   public  double calculate(int i) {       return Math.sqrt(2.0 * i);   }}class SomeOtherClass {   void reuseObject() {      Calculator calculator = new Calculator();      for(int i = 0; i < 100; i++ ){          double r = calculator.calculate(i);          //use result r      }   }} 

The preceding code can be improved by making the calculate() method static. Another solution would be to create a static property, Calculator calculator ...

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