jeudi 25 juillet 2019

Which is better "nested if" or "if and multiple else if"?

Which code snippet has better performance?

Assuming that 'a' and 'b' are boolean variables.

First Code Snippet

if (a && b) {
    // path 1
} else if (a && !b) {
    // path 2
} else if (!a && b) {
    // path 3
} else {
    // path 4
}

Second Code Snippet

if (a) {
    if (b) {
        // path 1
    } else {
        // path 2
    }
} else {
    if (b) {
        // path 3
    } else {
        // path 4
    }
}

It seems that the second code snippet is doing less work but I don't know if nesting 'if conditions' have side-effects.

Aucun commentaire:

Enregistrer un commentaire