开发者

Run if statement in loop only once

Just curious if its possible. Consider follwing code:

boolean firstRow = true;

while{row = result.next())
{
    if(firstRow)
    {
        firstRow = false;
        //do some setup 
    }

    //do stuff
}

Its pseudo-code and question is general not开发者_如何学JAVA about some specific programming language.

My question: is it possible to write code that behaves exactly same but without using additional variable (in this case "firstRow"). In FOR loop its possible to check counter variable value but lets leave FOR loops out of this question.


Yes, do your setup before you start the loop and change it to a do..while. For example:

if (row = result.next()) {
  //do some setup 
  do {
    //do stuff
  } while (row = result.next());   
}


Well, there are some options. The first would be to move the "setup" code outside the loop. If you don't care that this would cause the setup to happen even when you never iterate at all, that is probably the best option. If you do care about that, you could add the loop condition to the if check.

if(row = result.next())
{
    //do some setup 
}
for (;row;row=result.next()) 
{
    //do stuff
}

Another would be to make your loop as simple as possible, and trust your compiler's optimizer to do the "unrolling" described above. It probably will, if you set the optimization options high enough.


if(row = result.next())
{
    //do some setup
    while(row) 
    {
        //do stuff
        row = result.next();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜