Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); //Suppose i'm passing these through another function
checkb(false); //so it makes sense for me doing these
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 checking for "not conditions" make the code run faster or does the checking of "not condition" don't even affect the performance? (Suppose I'm building a complicated node.js server that has many of these type of functions.)

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

I was just wondering if it affects the performance (practically or theoretically).

like image 660
Daniel Cheung Avatar asked Jun 28 '15 07:06

Daniel Cheung


1 Answers

Short answer: No, it does not effect the computation time.

Long answer: Most Javascript engines (Spider Monkey and V8) internally use a Just in Time compiler which will iron over those differences during runtime.

In low level programming languages (read: C/C++ and the ilk), you may gain something if you are able to prevent branch mis-predicts, like in C++ code, but the gain is usually worth it only if you are doing Kernel programming or doing extreme micro-optimizations.


Theoretically, whether it makes a difference or not depends on what kind of compiler you are looking at. If you are looking at a compiler which can learn from code traces, e.g. a Just in Time compiler, then it will make a difference if a certain pocket of code is the hot spot or not. If you are looking at static compilers, it may mean that the compiler may use one less clock cycle in one of the cases (either if or else) by preventing a jmp, but it'll depend on the compiler implementation.

like image 70
musically_ut Avatar answered Sep 23 '22 21:09

musically_ut