Fastest way to set all values of an array?

后端 未结 14 2252
悲哀的现实
悲哀的现实 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:09

    I have a minor improvement on Ross Drew's answer.

    For a small array, a simple loop is faster than the System.arraycopy approach, because of the overhead associated with setting up System.arraycopy. Therefore, it's better to fill the first few bytes of the array using a simple loop, and only move to System.arraycopy when the filled array has a certain size.

    The optimal size of the initial loop will be JVM specific and system specific of course.

    private static final int SMALL = 16;
    
    public static void arrayFill(byte[] array, byte value) {
      int len = array.length;
      int lenB = len < SMALL ? len : SMALL;
    
      for (int i = 0; i < lenB; i++) {
        array[i] = value;
      }
    
      for (int i = SMALL; i < len; i += i) {
        System.arraycopy(array, 0, array, i, len < i + i ? len - i : i);
      }
    }
    
    0 讨论(0)
  • 2020-12-04 18:10
       /**
         * Assigns the specified char value to each element of the specified array
         * of chars.
         *
         * @param a the array to be filled
         * @param val the value to be stored in all elements of the array
         */
        public static void fill(char[] a, char val) {
            for (int i = 0, len = a.length; i < len; i++)
                a[i] = val;
        }
    

    That's the way Arrays.fill does it.

    (I suppose you could drop into JNI and use memset.)

    0 讨论(0)
提交回复
热议问题