Improvement to switch-case statement
Adam D. Ruppe
destructionator at gmail.com
Wed Dec 31 15:22:32 PST 2008
On Thu, Jan 01, 2009 at 12:45:39AM +0200, Yigal Chripun wrote:
> IMO, either the switch statement should remain the low level
> (effiecient) construct as in C, or replaced by a general mechanism of
> pattern matching.
This wouldn't be any less efficient than any other switch statement; writing
case 2..5:
code;
break;
could just be magically converted into
case 2:
case 3:
case 4:
case 5:
code;
break;
That's not ideal when doing a huge range; I'd probably write it like so in asm:
cmp ax, 2
je code
cmp ax, 3
je code
cmp ax, 4
je code
cmp ax, 5
je code
; more cases....
jmp default
code:
; the code from inside the case goes here
Doing a bigger range could let you write something more like this:
cmp ax, 2
jl more_cases
cmp ax, 5
jg more_cases
; case 2..5 code here
more_cases:
; check other cases
jmp default
Or maybe:
cmp ax, 2
jge code
more_cases:
; more cases....
jmp default
code:
cmp ax, 5
jg more_cases
; proceed with the code inside
If I was writing it by hand, I'd probably pick one based on what other cases
there are to try and minimize the jumps. The compiler could surely do the same.
Anyway though, the point is the simple range in the case is at least no
worse than writing it in C with a series of cases, and might be better, since
the compiler can condense it all down into just a few instructions rather
than a big laundry list.
Finally, the D switch statement already does strings as cases, which the
one in C would never do; the D switch already has moved beyond it, so it
wouldn't be out of character for it to pick up the ranges too.
--
Adam D. Ruppe
http://arsdnet.net
More information about the Digitalmars-d
mailing list