When I initialize an array in Java like:
float[] array = new float[1000];
all elements are initialized to 0. Is that also the case when I allocate a direct buffer like this:
FloatBuffer buffer = ByteBuffer.allocateDirect(4*1000).asFloatBuffer();
? I always seem to get only zeroes, but perhaps it's implementation dependent...
A direct buffer is a chunk of native memory shared with Java from which you can perform a direct read. An instance of DirectByteBuffer can be created using the ByteBuffer. allocateDirect() factory method.
In Java, all array elements are automatically initialized to the default value. For primitive numerical types, that's 0 or 0.0 .
By default in Java, data types like int, short, byte, and long arrays are initialized with 0. So, if you create a new array of these types, you don't need to initialize them by zero because it's already their default setting.
A buffer is essentially a block of memory into which you can write data, which you can then later read again. This memory block is wrapped in a NIO Buffer object, which provides a set of methods that makes it easier to work with the memory block.
It looks like the answer is probably.
Looking at the implementation of ByteBuffer
, it uses DirectByteBuffer
under the hood. Taking a look at the implementation source code of Android, it has this comment:
Constructs a new direct byte buffer of the given capacity on newly allocated OS memory. The memory will have been zeroed.
So, when you allocate a buffer, all of the memory contents will be initialized to zero. The oracle implementation also does this zeroing.
This is an implementation detail though. Since the javadoc says nothing about the zeroing, it's technically incorrect to rely on it. To be correct, you should really zero the buffer yourself. In practice, if you're really worried about performance for some reason, you could leave it out, but be warned that some implementations of the JVM might not do this zeroing.
Looking at the Javadoc for Java 7 and also Java 8
it now says
The new buffer's position will be zero, its limit will be its capacity, its mark will be undefined, and each of its elements will be initialized to zero. Whether or not it has a backing array is unspecified
So there is no longer any need for you to zero them yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With