Out of curiosity, I have tested the performance of two versions of that method - one with a loop and the other one using guava:
public int[] loop() {
int[] a = new int[100];
for (int i = 0; i < 100; ++i) {
a[i] = i;
}
return a;
}
public int[] guava() {
Set<Integer> set = ContiguousSet.create(Range.closed(0, 99), DiscreteDomains.integers());
int[] a = Ints.toArray(set);
return a;
}
Here are the results:
Benchmark Mean Mean error Var Units
loop 79.913 5.671 30.447 nsec/op
guava 814.753 46.359 2034.726 nsec/op
So the guava()
method runs in 814 ns +/- 46ns vs. 80 ns +/- 5ns for the loop()
method. So loop()
is about 10x faster. If you call that method a few times, the 800 nanoseconds don't matter, if you call it very often, writing the loop is probably better.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…