Which is better if chain If-Else-If or multiple If

Let's say I have a random number.

Which is more efficient:

if (num == 1) {

} else if (num ==2) {

} else if (num == 3) {

} else if (num == 4) {

} else if (num == 5) {

} else {};

      

or

if (num == 1) {};
if (num == 2) {};
if (num == 3) {};
if (num == 4) {};
if (num == 5) {};

      

are there many different characteristics?

Or do I need a chain of switches?

+3


source to share


5 answers


If you have a small number of situations that you want to handle separately (and you use a number to differentiate), the operator Switch

will provide clearer logic to someone (including you) who is trying to read or modify your code.

If / else if

chains can be misunderstood later



Sequential statements If

mean you are constantly checking for a situation that you know is wrong

+3


source


A bit late to the party, but apart from other valid answers:
what if you could directly name your intended subcode (almost) (if you have a lot of options) ....

I have a different solution (you had other options):

var switchArr=[ //skipping 0
, function(){ /* do stuff for 1 */ }
, function(){ /* do stuff for 2 */ }
, function(){ /* do stuff for 3 */ }
]; // you could also set them directly if you have irregular (large) intervals

if(switchArr[num]){
  switchArr[num]();
} else {
  //defaults
}

      

EDIT: Alternatively (expanding on the above concept) with an object (because the order doesn't have to be guaranteed like an array) and some closure and an easy way to pass num

to the handler function:

var switcher=(function(){
  var N, F={
   default: function(){ alert('default function for '+N); }
  ,      1: function(){ alert('doing stuff for '+N);  }
  ,      2: function(){ alert('other stuff for '+N);  }
  ,      5: function(){ alert('I am function '+N);  }
  };

  return function(n){ F[N=n] ? F[n]() : F.default(); };
})();

num=3; switcher(num);  // default function for 3
num=5; switcher(num);  // I am function 5

      

Depending on the use case, one of the above (or hybrid ones) might be the best solution. If the runtime is at the beginning of the line, do not use a helper function (that does the check), as this saves the function call.

EDIT 2:

The comments suggest using this alternative:



Contrary to popular belief (which javascript / ecmascript uses switch

to "jump directly" to the starting point in a code block), the switch statement in modern browsers evaluates expressions case

using the ===

strict comparison operator (so expressions must match without type conversion) in the order in which they are ( case

not default

) appear until a matching value is found (after which it will be before 'a break

or return

when it is encountered within a function or the code block ends, so it default

can appear anywhere in the code block, not just at the end). This is because the ECMAScript v3 standard allows each case to follow an arbitrary expression .

Note (for older browsers) that the switch statement is implemented in JavaScript 1.2, but does not fully conform to the ECMAScript specification. In JavaScript 1.2, case expressions must be literals or compile-time constants that do not include any variables or method calls. In addition, while ECMAScript allows switch and case expressions to be of any type, JavaScript 1.2 and JavaScript 1.3 require expressions to evaluate to primitive numbers, strings, or booleans.
Source: JavaScript: The Definitive Guide (4th ed.)

See the similarity to if-chain? The difference lies in the ability to fail (to end / break / return).
So the amount of comparative work (in an example where you have many different cases) is the same (at least by spec, not guaranteed to implement an interpreter that varies a lot among versions).

Optimal optimization (usually not frowned upon) involves tuning code that should have a predictable, relatively scalable (in terms of host capabilities) execution time. In my proposal (intended to show ways of thinking outside the box), you have a small, fixed number of steps before your payload gets executed (which you can guarantee according to the language specification).

This leaves "comprehensible", which is a tricky question because it has a lot to do with "intent" and "readability", thus opening up a can of worms for different points of view / options / mantra / best practices, most of which have different meanings ( or just simply shouldn't / shouldn't apply) to "javascript" (for web apps) (in my opinion).
Many different approaches can be thought of using comments etc. (Or a second example that uses an object), and various coding styles / patterns that will ease the initially perceived obstacle of "clear code".
At the end of the day, you should ideally have a well-documented "raw" ((gzip-) pre-optimized where applicable (you don't want to maintain / debug both the original and "compiled" code)), but post minified (no document / comments minified var-names, etc.) code into the browser (in production).

Finally, in terms of performance, again depending on what you are trying to do (and many cases are involved), the version of the array (without the helper function) will be the smallest and fastest for a number of numeric cases. The object then has its strength in (irregular) numeric intervals and string switches. However, as always, the (supported target) hosts / browsers should be checked to assess their performance. However, so far, in my experience, dealing with many cases, this is the winner.

Final note, when you're dealing with a known set of cases, for example, you didn't even need to check if a case exists, let alone a helper function .. speed to win (in that case).

+2


source


In general, else-if has better performance than chaining. But using a switch would be a better choice in this case.

+1


source


An efficient way to check is with a switch statement, not an if,

switch(num) {  
  case 1:  
    do something;
    break;  
  case 2:  
    do something;
    break;  
  default:  
    default do something;  
} 

      

+1


source


The best approach, especially for large codes, is the if else statement (or even better case). Using multiple if statements causes the computer to perform unnecessary calculations. For example:

if (5 > 3){
alert("True");
} 
else{
alert("False");
}

      

This is a logical expression. In the above example, cpu checks if (5> 3), which returns true and stops (it won't execute or check else). The same, but using multiple if

if (5 > 3){
    alert("True");
    } 
if (5 < 3){
alert("False")}

      

It will do the same as the previous code, but now it will do 2 calculations instead of one

0


source







All Articles