Search code examples
javaarraysunsafe

Avoid array initialization in Java


Is it possible to avoid array zeroing/initialization in Java?

I need to quickly allocate fresh byte arrays of fixed length that will completely be filled with predefined data. Therefore, I don't need the JVM to automatically zero the array on instantiation and I certainly don't mind if the array contains junk. All I need is constant time array allocation, which unfortunately becomes O(n) due to the mentioned zeroing issue.

Would using unsafe help?


Solution

  • JVM always initializes arrays. But you can reuse the same array and it will be initialized once.