?

Log in

No account? Create an account

Previous Entry | Next Entry

WTF Coding: Example code for how NOT to...

Example code from the .NET Framework 4 documentation:

     public class myReverserClass : IComparer  
     {
        // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
  
        int IComparer.Compare( Object x, Object y )  {
            return( (new CaseInsensitiveComparer()).Compare( y, x ) );
        }
     }


Can you see my "WTF"? This comparer is used to SORT ARRAYS later on in the same examples ("System.Array.Sort" method). Which means that the "Compare" method will be called "n" times - where the exact number "n" depends on the internal workings of the sort algorithm but certainly will be at least the number of elements in the array. Why on earth would anybody (even within a GC'd environment!) allocate a new comparer object for every comparison requested?? How about my usual way of implementing such a thing:

     public class myReverserClass : IComparer  
     {
	private _Wrapped = new CaseInsensitiveComparer();
        // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
  
        int IComparer.Compare( Object x, Object y )  {
            return( _Wrapped.Compare( y, x ) );
        }
     }


There. One object created instead of "n". Eventually, the original suggestion is going to cause performance problems. Not for 5-10 element arrays, but for 1000 arrays of 1000 elements? You WANT every bit of performance in the innermost loop of a sort algorithm.

What bothers me here: People are going to implement it like that - not only here, but everywhere similar. "Because MS does so in their samples, there must be a reason." And .NET ends up with a worse and worse reputation by the minute. Not because it is "slow by design". Far from it. But because people are coding it "as slow as possible" most of the times. Sometimes I wonder if the guys who write these examples are from the C++ group at MS, sabotaging C#.

Tags:

Latest Month

September 2018
S M T W T F S
      1
2345678
9101112131415
16171819202122
23242526272829
30      

Tags

Powered by LiveJournal.com
Designed by Katy Towell