if-continue vs 嵌套 if (if-continue vs nested if)


問題描述

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 ms813Oliuser3437460)

參考文件

  1. if‑continue vs nested if (CC BY‑SA 2.5/3.0/4.0)

#continue #java #nested-if






相關問題

skrip shell: loop bersarang dan lanjutkan (shell script : nested loop and continue)

syntaxError:“繼續”在循環中不正確 (syntaxError: 'continue' not properly in loop)

php continue - 替代方式? (php continue - alternative way?)

Python 中的歐拉 #4 (Euler #4 in Python)

if-continue vs 嵌套 if (if-continue vs nested if)

如何返回上一個 while 循環? (How do I return to the previous while loop?)

php foreach 繼續 (php foreach continue)

在while循環中繼續的奇怪行為 (weird behaviour of continue in while loop)

是否可以使用 'yield' 來生成 'Iterator' 而不是 Scala 中的列表? (Is it possible to use 'yield' to generate 'Iterator' instead of a list in Scala?)

BASH:在 for 循環中使用 continue (BASH: Using a continue in a for loop)

rand() 函數後繼續指令的問題 (Problem with continue instruction after rand() function)

在tictactoe遊戲中重複輸入錯誤 (Error in repeating input in a tictactoe game)







留言討論