[Mono-dev] Faster
Alex
xtzgzorex at gmail.com
Thu Mar 24 12:17:58 EDT 2011
Hi
I like the idea, and it could probably yield some performance gains,
but I'm worried about readability and maintainability. Wouldn't doing
the try-catch for NullReferenceException severely injure those two?
Would it be possible to do the optimization at runtime instead?
Cheers,
Alex
2011/3/24 Miguel de Icaza <miguel at novell.com>:
> 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
> _______________________________________________
> Mono-devel-list mailing list
> Mono-devel-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-devel-list
>
More information about the Mono-devel-list
mailing list