当前位置: 动力学知识库 > 问答 > 编程问答 >

java - if-continue vs nested if

问题描述:

I'm implementing some collision detection. Over time, by continually adding extra checks as the complexity of the project has grown I've accidentally stumbled into a pattern that looks like the following:

for (GameObject o1 : collisionObjects) {

for (GameObject o2 : collisionObjects) {

if(o1 == o2){

continue;

}

if(!(o1.isSolid() && o2.isSolid())){

continue;

}

//several more checks

//all of the early-out conditions are passed so do

//do some intersection checks here

}

}

Looking at the whole accumulated code later, I thought if I was to refactor this I would use nested ifs:

for (GameObject o1 : collisionObjects) {

for (GameObject o2 : collisionObjects) {

if(o1 != o2){

if(o1.isSolid() && o2.isSolid()){

//all conditions are met so do collision detection

}

}

}

}

From a readability perspective I quite like the first example, as it breaks out all of the conditions clearly, and doesn't leave me with a deep set of nested ifs.

From an efficiency perspective, the first requires more comparisons each time.

Which of these methods is better? Are there any side effects that I'm unwittingly invoking by using the first rather than the second?

网友答案:

If you're worried about the first requiring more checks why not negate your logic and fold the second if statement into the first? e.g.

if(o1 != o2 && o1.isSolid() && o2.isSolid()) {
    // extra stuff
}

with lazy analysis of the boolean logic the statement will fail as soon as a false is reached.

If you're concerned about performance though I think it's FAR more important to look into collision detection strategies. For example, Oct-trees, BSP etc.

网友答案:

Are there any side effects that I'm unwittingly invoking by using the first rather than the second?

Both are fine and I don't see any significant advantage of one over the other.

But if you are serious and want to make something efficient (for example in a 3D world with tens of thousands of objects to check for collision consistently), you will be looking at tree. Particularly quad-tree. This is how games actually did their collision detection.

This is a rather large topic if you study gaming in school.

分享给朋友:
您可能感兴趣的文章:
随机阅读: