When the complier is optimizing the C++ code, branch prediction due to logical construct (if-else, switch-case, ? : ternary operator) brings a major challenge. Changing the problem to minimize its effect results in significant optimized code.

 

Now, JavaScript is a "multi-paradigm language", but majorly conceived as functional language. Do we have similar branch prediction challenges when we are using if-else? And does the JS engines (Charka for IE) optimization teams face same challenges when dealing with if-else?

 

OAN: According to object-oriented designs and patterns, (if we can and where we can) we should avoid if-else in favor of polymorphism (or with event based programming). If we are able to solve if-else problem using polymorphism, would it be as optimized as a code without branching?

 

Now back to Charka, if the compiler/interpreter guys have same branching challenges in JavaScript, can we (the developers) convert the following construct:

 

if(ConditionX) {
    statementX1;
    statementX2;  //multiple statements in the block
} else {
     statementY1;  // single statement in the block
}

 

into:

 

((ConditionX) && ((function()  {
    statementX1; 
    statementX2;
})() || true)) || (statementY1 || true);

 

to avoid branch prediction altogether?

 

Is it universally valid for all scenarios?

 

If the above perceptions are true, can we make the compiler to always see those if-else constructs as chained logical operations?

 

Can we do the same in other languages compilers; C/C++/C#?