Fastest way to set all values of an array?

后端 未结 14 2274
悲哀的现实
悲哀的现实 2020-12-04 17:47

I have a char [], and I want to set the value of every index to the same char value.
There is the obvious way to do it (iteration):

<         


        
14条回答
  •  [愿得一人]
    2020-12-04 18:06

    Java Programmer's FAQ Part B Sect 6 suggests:

    public static void bytefill(byte[] array, byte value) {
        int len = array.length;
        if (len > 0)
        array[0] = value;
        for (int i = 1; i < len; i += i)
            System.arraycopy( array, 0, array, i,
                ((len - i) < i) ? (len - i) : i);
    }
    

    This essentially makes log2(array.length) calls to System.arraycopy which hopefully utilizes an optimized memcpy implementation.

    However, is this technique still required on modern Java JITs such as the Oracle/Android JIT?

提交回复
热议问题