dimanche 28 juin 2015

JS - If condition with only 1 else, does checking order affect performance?

I was working on a project and this problem popped into my head. I am not sure if there is already a post like this but I have found none.

Let say if I have this:

function checks(s) {
    if (s.length == 4 && s[0] == "a") {
        //action
    } else {
        //other action
    }
}
checks("a001");
checks("else");
checks("else");
checks("else");

and this:

function checkb(b) {
    if (b) {
        //action
    } else {
        //other action
    }
}
checkb(true);
checkb(false);
checkb(false);
checkb(false);

Since either way the if-statement is going to have to check once of the conditions, if the frequency of the actions are known (e.g. I know that the else part is performed most often). Does the checking for "not conditions" make the code run faster or does the checking of "not condition" don't even affect the performance?

Addition question: Do most programming languages do the same too?

Aucun commentaire:

Enregistrer un commentaire