If-else-if versus map

Suppose I have an if else-if chain like this:

if( x.GetId() == 1 )
{
}
else if( x.GetId() == 2 )
{
}
// ... 50 more else if statements

What am I interested in if I save the map, will it be better in terms of performance? (assuming the keys are integers)

+5
source share
7 answers

Maps (usually) are implemented using red-black trees, which give an O (log N) search, since the tree is constantly in equilibrium. Your linear list of if statements will be the worst case of O (N). So, yes, the map will be significantly faster to search.

switch, , if. , , O (1), , undefined; . switch C ++.

, , , , ( I/ , 99% 1 ):

unsigned char single_bit_index(unsigned char bit) {
    // Hard-coded balanced tree lookup
    if(bit > 0x08)
        if(bit > 0x20)
            if(bit == 0x40)
                return 6;
            else
                return 7;
        else
            if(bit == 0x10)
                return 4;
            else
                return 5;
    else
        if(bit > 0x02)
            if(bit == 0x04)
                return 2;
            else
                return 3;
        else
            if(bit == 0x01)
                return 0;
            else
                return 1;
}

3 8 , , - - 4- , 1 - 8 .

, , , , 8 , , : 1, 2, 4, 8, 16, 32, 64 128. 128 , 8 , , , .

+10

?

swich(x.GetId())
{
  case 1: /* do work */ break; // From the most used case
  case 2: /* do work */ break; 
  case ...: // To the less used case
}

EDIT:

( , x.GetId 50)

+5

switch - ,

+2

switch. x.GetId() , ( ) 25 , .

, , , , , . ( 1 50), . , .

0

, , , .

, switch , . , , . , , , , .

[, switch if/else]

A map , switch . , , switch , .

A map , , . A switch , , .

. , , . , .

0

, .

#include <cstdio>
#include <cstdlib>
#include <ctime>

const unsigned int Max = 4;

void f1();
void f2();
void f3();
void f4();
void (*vp[Max])();

int main()
{
    vp[ 0 ] = f1;
    vp[ 1 ] = f2;
    vp[ 2 ] = f3;
    vp[ 3 ] = f4;

    srand( std::time( NULL ) );
    vp[( rand() % Max )]();
}

void f1()
{
    std::printf( "Hello from f1!\n" );
}

void f2()
{
    std::printf( "Hello from f2!\n" );
}

void f3()
{
    std::printf( "Hello from f3!\n" );
}

void f4()
{
    std::printf( "Hello from f4!\n" );
}
0

, . , , . .

/ , YES. - , . STL , , , , .

, std:: map, mymap,

thisvar = mymap[x.getID()];

, 50

if(x.getID() == ...){thisvar = ...;}

. , .

, , - /. getID() getName() - , . .

. , , .

, ID, . switch-case, if . . : if-else , , , , 100% , , , , 'd .

, , . , , , , .

0

All Articles