Any shortcut to initialize all array elements to zero?

后端 未结 14 2564
北恋
北恋 2020-11-28 18:12

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

14条回答
  •  有刺的猬
    2020-11-28 18:35

    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.

提交回复
热议问题