Effective switch statement

In the next two versions of the switch, I wonder which version is effective.

1

string* convertToString(int i)
{
    switch(i)
    {
    case 1:
        return new string("one");
    case 2:
        return new string("two");
    case 3:
        return new string("three");
        .
        .
    default:
        return new string("error");
    }
}

2:

string* convertToString(int i)
{
    string *intAsString;
    switch(i)
    {
    case 1:
        intAsString = new string("one");
        break;
    case 2:
        intAsString = new string("two");
        break;
    case 3:
        intAsString = new string("three");
        break;
        .
        .
    default:
        intAsString = new string("error");
        break;
    }
return intAsString;
}

1: has multiple return statements, will this cause the compiler to generate additional code?

+3
source share
14 answers

This is a premature optimization concern.

The first form is clearer and has fewer source lines, which is a good reason for choosing it (in my opinion), of course.

You should (as usual) profile your program to determine if this feature is enabled even in the "hot list" for optimization. This will tell you if there is a performance penalty when using break.

, , . , " " .

+29

.

, , - . ? ? ?

+10

. :

  • , , .
  • , ( ) .
+6

, , , .

++ , , , . , , , 2 10 - switch-case.

, : Mu.

+3

switch if . case switch.

, , .

static const char *numberAsString[] = {
    "Zero",
    "One",
    "Two",
    "Three",
    "Four",
    "Five",
    "Six",
};

const char *ConvertToString(int num) {
  if (num < 1 || num >= (sizeof(numberAsString)/sizeof(char*))) 
    return "error";
  return numberAsString[num];
}
+3

, , , .

+2

, , .

+1

. , .

+1

- :

void CScope::ToStr( int i, std::string& strOutput )
{
   switch( i )
   {
   case 1:
        strOutput = "Some text involving the number 1";

   ... etc etc
}

, , . , , , .

+1

:

static char const g_aaczNUMBER[][] = 
    {
        {"Zero"}, { "One" }, ...
    };

static char const g_aczERROR[] = { "Error" };

char* convertIntToString(int i) const { 
    return i<0 || 9<i ? g_aczERROR : g_aaczNUMBER[i]; 
}
+1

switch [*], ( , ). switch, :

string *convertToString(int i) {
    const char *str;
    switch(i) {
        case 1 : str = "one"; break;
        // etc
        default : str = "error"; break;
    }
    return new string(str);
}

, , :

const char *values[] = {"error", "one", ... };

string convertToString(unsigned int i) {
    if (i >= sizeof(values)/sizeof(*values)) i = 0;
    return values[i];
}

, , , . , , .

[*] ​​ , , , , . .

+1

. , . № 2 - , - , .

0

, return . ( ) .

0

, , , .

, . , .

, if else, , , , , .

0

Source: https://habr.com/ru/post/1724749/


All Articles