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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.