In C/C++
I used to do
int arr[10] = {0};
...to initialize all my array elements to 0.
Is there a similar shortcut in
The int values are already zero after initialization, as everyone has mentioned. If you have a situation where you actually do need to set array values to zero and want to optimize that, use System.arraycopy
:
static private int[] zeros = new float[64];
...
int[] values = ...
if (zeros.length < values.length) zeros = new int[values.length];
System.arraycopy(zeros, 0, values, 0, values.length);
This uses memcpy
under the covers in most or all JRE implementations. Note the use of a static like this is safe even with multiple threads, since the worst case is multiple threads reallocate zeros
concurrently, which doesn't hurt anything.
You could also use Arrays.fill
as some others have mentioned. Arrays.fill
could use memcpy
in a smart JVM, but is probably just a Java loop and the bounds checking that entails.
Benchmark your optimizations, of course.