Code Performance: if-if-if or if-else if-else if or switch case

If we have condition where we have to select one option among number of options then we can adopt following control statements:

First Way and Worst Way

string strMsg = “”;

if(color==”black”) {

strMsg = “Color is black.”;

}

if(color==”blue”) {

strMsg = “Color is blue.”;

}

if(color==”red”) {

strMsg = “Color is red.”;

}

Second Way and Worst Way

string strMsg = “”;

if(color==”black”) {

strMsg = “Color is black.”;

}

else if(color==”blue”) {

strMsg = “Color is blue.”;

}

else if(color==”red”) {

strMsg = “Color is red.”;

}

Third Way and Best Way

string strMsg = “”;

switch (caseSwitch)
{
case “black” : {

strMsg = “Color is black.”;

break;

}

case “blue” : {

strMsg = “Color is blue.”;

break;

}

case “red” : {

strMsg = “Color is red.”;

break;

}

default;

{

strMsg = “No Color.”;

}

}

In above,  3 control statements switch case is best.

Vikas Jindal

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s