Fastest way to set all values of an array?

后端 未结 14 2280
悲哀的现实
悲哀的现实 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 17:47

    As another option and for posterity I was looking into this recently and found a solution that allows a much shorter loop by handing some of the work off to the System class, which (if the JVM you're using is smart enough) can be turned into a memset operation:-

    /*
     * initialize a smaller piece of the array and use the System.arraycopy 
     * call to fill in the rest of the array in an expanding binary fashion
     */
    public static void bytefill(byte[] array, byte value) {
      int len = array.length;
    
      if (len > 0){
        array[0] = value;
      }
    
      //Value of i will be [1, 2, 4, 8, 16, 32, ..., len]
      for (int i = 1; i < len; i += i) {
        System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
      }
    }
    

    This solution was taken from the IBM research paper "Java server performance: A case study of building efficient, scalable Jvms" by R. Dimpsey, R. Arora, K. Kuiper.

    Simplified explanation

    As the comment suggests, this sets index 0 of the destination array to your value then uses the System class to copy one object i.e. the object at index 0 to index 1 then those two objects (index 0 and 1) into 2 and 3, then those four objects (0,1,2 and 3) into 4,5,6 and 7 and so on...

    Efficiency (at the point of writing)

    In a quick run through, grabbing the System.nanoTime() before and after and calculating a duration I came up with:-

    • This method : 332,617 - 390,262 ('highest - lowest' from 10 tests)
    • Float[] n = new Float[array.length]; //Fill with null : 666,650
    • Setting via loop : 3,743,488 - 9,767,744 ('highest - lowest' from 10 tests)
    • Arrays.fill : 12,539,336

    The JVM and JIT compilation

    It should be noted that as the JVM and JIT evolves, this approach may well become obsolete as library and runtime optimisations could reach or even exceed these numbers simply using fill(). At the time of writing, this was the fastest option I had found. It has been mentioned this might not be the case now but I have not checked. This is the beauty and the curse of Java.

提交回复
热议问题