Usually small, short-lived objects are almost free. Consider f1 and f2
static Entry f1(int i){ return new Entry(i); } static Entry entry = new Entry(0); static Entry f2(int i){ entry.i=i; return entry; } static class Entry { Entry(int i){ this.i=i; } int i; int get(){ return i; } }
This is a realistic test example of the problem you described - reusing the same object in an iteration, as well as creating a new object in an iteration. In both cases, some data is stored in the object and transferred to the call site to be read.
Allows you to profile it, extract a billion records and read the data stored in each, in three different ways.
int r = 0; for(int i=0; i<1000000000; i++) { test0: r += i; test1: r += f1(i).get(); test2: r += f2(i).get(); } print(r);
The number I got, test2 is as fast as test0 ; test1 slower than test2 , only one processor cycle per iteration . (I think the difference is in several machine instructions, and the CPU pipelines them in one cycle)
If you still do not believe it, fully implement the proposed "effective" solution, compare it with the supposedly "wasteful" implementation and look at the difference for yourself. You will be amazed.
source share