开发者

Java for loop to iterate and cycle multiple variables until condition met

I've written the following which does what I want it to do, but I think there's a faster way than doing a conditional statement in the for loop.

int i,j,k,l;
int[] X = new int[] {111,222,333,444};
int XL = X.length;

for (i=0, j=1; i<XL; j=(j<XL-1)?j+1:0, i++) {
  println("i:" +i +" j:" + j);
}

// returns:
// i:0 j:1
// i:1 j:开发者_Go百科2
// i:2 j:3
// i:3 j:0


Taking a different angle on the problem than just saying "do x to make the code 50% faster", how have you tested the code and how have you determined that it's too slow?

Java's JIT compiler these days is very, very good at what it does, making these sorts of micro optimisations so you don't have to. If you start doing ridiculous amounts of low level optimisations and obfuscating your code somewhat silly:

  • You may or may not achieve a small speed increase
  • You will make your code near unmaintainable and difficult to read
  • You may trick the JIT compiler into not making optimisations it would have done otherwise (since it understands common Java idioms much more than obfuscated code.)

If you still, definitely, and unavoidably need every last speed increase from your application then the best thing to do is just write these bits in assembler. If you're just trying to make things a fraction faster for the sake of it though, the best real world advice is almost always "don't bother".


Kerrek SB's comment is my preferred solution. Here it is rewritten to a bit more generic:

String[] X = new String[] {"AAA", "BBB", "CCC", "DDD"};
int XL = X.length;

for (int i=0; i<XL; i++) {
  println("i:" +X[i] +" j:" + X[(i+1)%XL] );
}

will return:

i:AAA j:BBB
i:BBB j:CCC
i:CCC j:DDD
i:DDD j:AAA


First, your for loop is not all that confusing as it is and you could add some comments to make it more understandable.

If you wanted to rewrite it with readability in mind, you could do this with one indexor.

int i; 
int[] X = new int[] {111,222,333,444}; 


for (i=0; i < X.length; i++) { 
  println("i:" +i +" j:" + (i < X.lenght -1) ? i + 1 : 0); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜