2

I have a Tuner App and I have heavy computations in background. I have noticed that I have had frequent garbage collections when computing. I have replaced:

float someBigArray = new float[bigNumber];

with global array:

 if (someBigArray == null) {
        someBigArray = new float[bigNumber];
    } else {
        Arrays.fill(someBigArray , 0f);
    }

This array is used when computing FFT and this is called multiple time per second. I've get rid of frequent garbage collections but I'am not sure that it is more efficient solution. Maybe there is some better idea.

Wrobel
  • 1,042
  • 12
  • 21
  • We might need to have more context: what is the purpose of your `someBigArray`? With other words: what are you going to do with that array? – KarelG Mar 09 '18 at 07:29
  • This array is used when computing FFT and this is called multiple time per second. I've edited the question too. – Wrobel Mar 09 '18 at 07:36
  • https://stackoverflow.com/questions/9128737/fastest-way-to-set-all-values-of-an-array -- this has examples that use more performant solutions than Arrays.fill – PJ Fanning Jan 10 '22 at 13:09
  • it appears that in modern Java runtimes, Arrays.fill is now more performant due to http://psy-lob-saw.blogspot.com/2015/04/on-arraysfill-intrinsics-superword-and.html – PJ Fanning Jan 10 '22 at 14:43

1 Answers1

0

It is (probably1) faster than to recycle an array (and reinitialize it) than it is to allocate a new one.

Can you do better than re-initializing? Probably not!

However, if you are only using a small part of the big array each time, then re-initializing the whole array could be wasteful. (It may be worth keeping track of how much of the array you use each time.)


1 There are some scenarios involving arrays of references where it can be better to GC the array than having it tenured by the GC. For example, a reference to a new-space object in a tenured array will cause the new object to not be collected in a new-space collection.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216