[Mono-list] [Off-topic] "if else" or "switch" ?

Michal Moskal malekith@pld-linux.org
Sat, 16 Oct 2004 12:12:42 +0200


On Sat, Oct 16, 2004 at 11:36:30AM +0200, Mike Welham wrote:
> > I guess the entire idea behind the .NET is that the compiler don't have
> > to deal with choices like switch vs if -- the runtime is going to take
> > care of it. Using switch in the IL should be just a hint for the
> > runtime. So there is nothing to change in the mcs. The runtime is what
> > should be fixed, if anything.
> 
> I agree with this, but only up to a point. The JIT is very time-constrained,
> and if the high-level compiler can perform high-level optimizations it
> should. (When I say high-level optimizations I mean things like dead-code
> elimination or tail-call optimization.)

I wouldn't say that the tail-call optimization is high level. You have
the tail prefix in the IL, and this should be handled by the JIT. Sadly
neither mono nor .NET implement this as efficiently as the direct jump.
And MS .NET is particularly bad at it.  This is why we have special
cases in the Nemerle compiler for self tail calls (that are equivalent
to jumps to the beginning of the method).

But it doesn't mean it's the right way of doing it. I, for one, would
expect tail.call to be faster the call. And it isn't.

And about the DCE -- it of course depends on your source language what
you consider the dead code. But there is a category of code that is dead
in the IL, and this can be removed be the JIT. Mono JIT does it.

> On the discussion of switches, a good example would be a switch against a
> number of strings. If the compiler maps this to IL naively, it would end up
> being a very time-consuming operation with a number of string comparisons on
> each pass through the statement. If, however, the compiler were to map it to
> a hash table lookup, it would become a very cheap constant-time operation.

Agreed. This is more high level -- generating perfect matching over
strings is NP-complete, so the JIT is unlikely to do it right.

> I think there are a wide range of (runtime agnostic) optimizations that
> belong in .NET compilers, because they're just not feasible to spot and
> perform at JIT time.

Everything here is about the definition of high level :)

-- 
: Michal Moskal :: http://www.kernel.pl/~malekith :: GCS !tv h e>+++ b++
: ::: Logic is a nice contrast to the Real World. :: UL++++$ C++ E--- a?