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

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

Problem

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
  } 
Problem courtesy of: Amol M Kulkarni

Solution

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..

Solution courtesy of: pkp

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *