On 15/03/2010 07:19, Jae Hyuk Kwak wrote:

> I think that for the "speed" optimization, perfect hash way is the
> best candidate after jump table if it is applicable. 

  It should be pointed out that your article contains a false assumption
about how fast the various options are relative to each other:

> For example, when we have a piece of code like this:
> 
>     if( a == 1 ) doSomething1();
>     else if( a == 2 ) doSomething2();
>     else if( a == 3 ) doSomething3();
>     ....
>     else if( a == 40000 ) doSomething40000();
> 
> For each line, CPU, more precisely ALU, will evaluate each statement: "a ==
> 1", "a == 2" and so on. In other words, CPU need to calculate 40000 times
> for the same value "a".

  This is not true unless a is a volatile variable.  The compiler will
evaluate a once and then compare it against the constants.

> More intuitive representation for this testing can be like this:
> 
>     switch( a )
>     {
>     case 1: doSomething1(); break;
>     case 2: doSomething2(); break;
>     case 3: doSomething3(); break;
>     ...
>     case 40000: doSomething4000(); break;
>     }
> 
> This "switch statement" gives us an illusion that CPU will evaluate the
> value of "a" only one time.
> 
> According to an article on CodeGuru, however, "switch" statement will be
> replaced by "else if"

  It may, but in this case, the result is even better; the compiler will only
ever evaluate "a" once even if it *is* volatile.

    cheers,
      DaveK


Reply via email to