What is the performance impact of Arrays.setAll in java?

Viewed 86

I created a method that simply fills an array of Integer[] objects and I was wondering if there would be a performance difference between using the builtin Java method Arrays.setAll :

private static Integer generate_number(){
    return random.nextInt(9000);
}
    
public static void fill_array_with_randNumbers(Integer[] array){
    Arrays.setAll(array, i -> generate_number());
}

and doing it the old fashion way:

private static Integer generate_number(){
    return random.nextInt(9000);
}

public static void fill_array_with_randNumbers(Integer[] array){
    for(int i = 0; i < array.length; i++) {
        array[i] = generate_number();
    }
}
1 Answers

No, there is not difference if you check the java source of Arrays. It also use the loop to set variable.

/**
  * @param <T> type of elements of the array
  * @param array array to be initialized
  * @param generator a function accepting an index and producing the desired
  *        value for that position
  * @throws NullPointerException if the generator is null
  * @since 1.8
  */
public static <T> void setAll(T[] array, IntFunction<? extends T> generator) {
    Objects.requireNonNull(generator);
    for (int i = 0; i < array.length; i++) {
         array[i] = generator.apply(i);
    }
}

https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/Arrays.java

Related