Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch vs if-else branching control structure in Node.JS

Tags:

node.js

Which one is good to use when there is a large number of branching flow in Node.JS Program.

switch

switch(n)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if n is different from case 1 and 2
}

OR
if-else

if (condition1)
  {
    execute code block 1
  }
else if(condition2)
  {
    execute code block 2
  } 
else
  {
     code to be executed if n is different from condition1 and condition2
  } 
like image 298
Amol M Kulkarni Avatar asked Apr 05 '13 10:04

Amol M Kulkarni


2 Answers

For just a few items, the difference is small. If you have many items you should definitely use a switch. It give better performance than if-else.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if-else where the last item takes much more time to reach as it has to evaluate every previous condition first..

like image 94
pkp Avatar answered Oct 08 '22 22:10

pkp


switch(n)
{
case 1,3,4:
     execute code block 1
     break;
case 2,5,9,10:
     execute code block 2
     break;
default:
      code to be executed if n is different from first 2 cases.
}

To write down the if...else if...else steps for the above case, you will have to write the 'OR (||)' condition-statement and repeat the variable 'n' in the statement, Where as switch cases can be separated by just a comma ','. Thus switch is more readable for such a case.

like image 44
upendra patil Avatar answered Oct 08 '22 22:10

upendra patil