Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

java - shortest way of filling an array with 1,2...n

Is there anything as quick as this in java? ( quick in coding)

int [] a = {1..99};

or I have to go for this:

int [] a=new int[100];
for (int i=0;i <100;++i){
a[i]=i;
}
question from:https://stackoverflow.com/questions/16020741/shortest-way-of-filling-an-array-with-1-2-n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...