Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 30 Oct 2014 12:24:33 +0800
From:      bycn82 <bycn82@gmail.com>
To:        Erich Dollansky <erichsfreebsdlist@alogt.com>, FreeBSD Net <freebsd-net@freebsd.org>
Cc:        freebsd-ipfw <freebsd-ipfw@freebsd.org>
Subject:   Re: performance of the swtich/case statements
Message-ID:  <CAC%2BJH2xyKq_0R_4CdxZsYcrf%2B6aeqxRJCtpoTcT9YAX6za6xYQ@mail.gmail.com>
In-Reply-To: <20141030063053.12608314@X220.alogt.com>
References:  <009101cff386$29c30e50$7d492af0$@gmail.com> <20141030063053.12608314@X220.alogt.com>

next in thread | previous in thread | raw e-mail | index | archive | help
Hi,
According to my understanding in Java programming, the compiler will
automatically store the values into a table and jump to the correct one
according to the value only when the condition values are in running
number,

for example.

swtich(a){
case 1:  code block 1
case 2:  code block 2
case 3:  code block 3
case 4:  code block 4
default: code block 5
}

it will be handled by an array
1-->code block 1
2-->code block 2
3-->code block 3
4-->code block 4
others-->code block 5

so when the value N is greater than  or lesser than 1, it will be directly
jump to the "code block 5"
otherwise, it will jump to N, because call the cases are nice in running
numbers,

but when the cases are messy, it will by just like lots of if/else


On Thu, Oct 30, 2014 at 6:30 AM, Erich Dollansky <
erichsfreebsdlist@alogt.com> wrote:

> Hi,
>
> On Wed, 29 Oct 2014 22:39:34 +0800
> "bycn82" <bycn82@gmail.com> wrote:
>
> > It is using the switch/case statement to make the code clear in the
> >
> > I am not a C programmer, so I am not clear how the switch/case will be
> > optimized by the compiler in FreeBSD. But I used to write a compiler
> > by myself and I use a hash table to handle all the conditions in the
> > case statements because my compiler don't care about performance!,
> > But in C it is different, the case statement can only accept "int"
> > values, so I don't think it will use hash or what , it should be
> > directly use an array(), So whether it can be optimized it depends on
> > the conditions in the switch/case statements, and I noticed that the
> > cases statement in the 2 loops are not arranging the opcode in
> > running number, so does the compiler smart enough to optimize it?
> >
> >
> I did not check recently. It was already a long, long time ago, that
> compilers checked the limits and used the values as an index into a
> table to jump to the code. I hope that this did not get changed.
>
> With other words, the order in the code does not matter. The only
> optimisation the compiler can do, is not to use a table if the
> statement consists of a low number of entries only.
>
> Erich
>



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?CAC%2BJH2xyKq_0R_4CdxZsYcrf%2B6aeqxRJCtpoTcT9YAX6za6xYQ>