[Mono-dev] Faster

Miguel de Icaza miguel at novell.com
Thu Mar 24 12:00:56 EDT 2011


Hello guys,

Today in the shower I had an idea that I believe we could use to
improve the performance of our class library code.

Plenty of our class library code has code like this:

void Foo (Something x)
{
    if (x == null)
        throw new ArgumentNullException ("x");
    x.DoSomething ();
    x.AndThenMore ();
}

Arguably, if this could be inlined, and the JIT could prove that x is
not null, we would skip the first test, for example:

Foo (new Something ());

But this is the exception, in general, the JIT would not be able to
know this kind of information for even trivial uses like:

Foo (Bar.GetSomething ());

Rendering the optimization not very effective.

But what if we changed our code in Foo across our class libraries to
do this instead:

void Foo (Something x)
{
    try {
        x.DoSomething ();
    } catch (NullReferenceException e){
        if (x == null)
             throw new ArgumentNullException ("x");
        else
              throw;
    }
    x.AndThenMore ();
}

This has the advantage that the test for the value of "x" being null
is delayed until we actually need it.    The downside of course is
that DoSomething could actually take other forms and might end up
running code that we do not need before it touches x, for example,
this would be a problem:

// We should never add null values.
void AddToCache (Something x)
{
    cache.Add (x);
}

void Foo (Something x)
{
      if (x == null)
          throw new ArgumentNullException ("x");
      AddToCache (x);
}

If we rewrite the above code, we would end up with a bug like the one
I described.

Miguel


More information about the Mono-devel-list mailing list