vendredi 19 juillet 2019

c# Nested vs Flat If Else checking for words in positions

I have some c# code that takes a string question and converts each word to a list so I can check for certain words in certain positions to trigger different methods. I have it written into a large If Else statement and am wondering if a nested if else would be faster because it could narrow the conditions to check by the first word. See example below. Or would a flat If Else be faster? Is there a faster way to check for certain words in certain positions using substrings?

Nested if else

string question = "How long is the Mississippi River"
List<string> questionSplit = question.Split(' ').ToList();   

if (questionSplit[0] == "How")
{
    if (questionSplit[1] == "long")
    {
        MeasureLength();
    }
    else if (questionSplit[1] == "high")
    {
        GetElevation();
    }
}
else if (questionSplit[0] == "What")
{
    DoSomething();
}

else if (questionSplit[0] == "When")
{
    DoSomething();
}
else if (questionSplit[0] == "Where")
{
     DoSomething();
}

VS flat If Else

if (questionSplit[0] == "How" && questionSplit[1] == "long")
{
    MeasureLength();   
}
else if (questionSplit[0] == "How" && questionSplit[1] == "high")
{
    GetElevation();   
}
else if (questionSplit[0] == "What")
{
    DoSomething();
}

else if (questionSplit[0] == "When")
{
    DoSomething();
}
else if (questionSplit[0] == "Where")
{
     DoSomething();
}

Aucun commentaire:

Enregistrer un commentaire