問題描述
if‑continue vs 嵌套 if (if‑continue vs nested if)
我正在實施一些碰撞檢測。隨著時間的推移,隨著項目複雜性的增加,我不斷添加額外的檢查,我無意中發現了一個如下所示的模式:
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
}
}
稍後查看整個累積的代碼,我想如果我是為了重構這個我會使用嵌套的 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
}
}
}
}
從可讀性的角度來看,我非常喜歡第一個示例,因為它清楚地打破了所有條件,並且不會給我留下深刻的一組嵌套的 if。從效率的角度來看,第一種方法每次都需要更多的比較。
這些方法哪個更好?通過使用第一個而不是第二個,我是否會無意中調用任何副作用?
參考解法
方法 1:
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.
方法 2:
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.
(by ms813、Oli、user3437460)