import java.io.PrintWriter;
import java.util.Arrays;
public class temp {
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
double size = 1e8;
int a[] = new int[(int) size];
long start;
for (int j = 0; j < 4; j++) {
start = System.nanoTime();
for (int i = 0; i < size; i++) {
a[i] = Integer.MAX_VALUE;
}
print((System.nanoTime() - start) / 10e6);
a = new int[(int)size];
start = System.nanoTime();
Arrays.setAll(a, n -> Integer.MAX_VALUE);
print((System.nanoTime() - start) / 10e6);
a = new int[(int)size];
start = System.nanoTime();
Arrays.fill(a, Integer.MAX_VALUE);
print((System.nanoTime() - start) / 10e6);
print("");
}
out.close();
}
public static void print(Object o) {
out.write(o.toString() + 'n');
}
public static void printS(Object o) {
out.write(o.toString());
}
}
I wrote the above benchmark to see whether Arrays.fill, Arrays.setAll or for loop array assignment is the best option when considering performance.
When I executed the code, the results were unstable, sometimes the time elapsed can be oddly short/long. How can I improve it so that the results are more reliable?
Side question: how is fill faster than for loop even though the fill implementation is nearly as similar as for loop?
14.92577
14.57896
11.24327
22.44939
7.48866
8.61509
19.83225
12.75963
11.79384
26.21852
10.34034
10.11821
Note: the results are printed in order: for loop, setall, fill, repeat
A non-external lib solution is preferred