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

Get Java 11 Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.