[Mono-devel-list] System.Reflection Performance

Ben Maurer bmaurer at users.sourceforge.net
Fri Jan 2 13:33:24 EST 2004


On Fri, 2004-01-02 at 13:08, Peter Williams wrote:
> Can we start a list somewhere? I'm thinking of basic, concrete things,
> like 
> 
> 	* use 'string.Length == 0' instead of 'string == ""'
> 	* use 'for (int = 0; i < arraylist.Count; i++)' instead of 'foreach
> (object item in arraylist)'
> 
> General optimization techniques are pretty much universal, but I think
> there's a lot of simple stuff like the above that it would be nice to
> have explicitly stated.

Well, all of these pretty much map out to `general optimization
techniques'

For example, in the string case, under the hood, the .Length == 0
translates to:

string->Length == 0

however, string == "" translates to:

String.Equals (string, "");

Thats pretty much a no brainer.

Foreach is even more of a nobrainer. The first case translates to:

for (int i = 0; i < arraylist.get_Count (); i++)
    ...

foreach translates to:

IEnumerable ie = arraylist.GetEnumerator ();

try {
   while (ie.MoveNext ()) {
       object item = ie.get_Current ();
       ...
   }
} finally {
   IDisposeable id = ie as IDisposeable;
   if (ie != null)
       ie.Dipose ();
}

Again, not hard to tell which one goes faster.

So, in general the thing to follow is:

      * Check to see if the compiler is generating extra IL for you
        (like in the foreach case, where it makes two extra variables
        and adds in exception catching). Look at the IL it generates.
      * Check if the JIT makes any of the items into instructions (such
        as String.Length).
      * If the compiler makes something into an instruction, it is
        likely to be fast
      * If it is a method call, where is it implemented? Look at the
        code, does it *LOOK* fast?

Honestly, i do not recommend writing if (string.Length == 0) when you
are writing code. It slows you down. You are likely to make a typo.

If you see that the method is slow *THEN* is the time to look at it.

Lists like this are pretty silly, I do not keep one -- either in my head
or on paper. When I look at how to make mcs faster, I don't say:

`Man, today, why dont i replace all =="" calls with .Length == 0'

rather I say:

`Method Foo () runs REALLY slow, whats up with that'

-- Ben




More information about the Mono-devel-list mailing list