[Mono-dev] Faster
Steve Bjorg
steveb at mindtouch.com
Thu Mar 24 12:06:04 EDT 2011
Is the cost of the if-null check greater than setting up an exception catch handler?
- Steve
---------------------------------
Steve G. Bjorg
MindTouch
San Diego, CA
619.795.8459 office
425.891.5913 mobile
http://twitter.com/bjorg
On Mar 24, 2011, at 9:00 AM, Miguel de Icaza wrote:
> 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