[Mono-dev] Question about performance improvement in C#

Brian Crowell mono-devel at fluggo.com
Mon Apr 17 14:38:52 EDT 2006

Rusmin Susanto wrote:
> In C, we can process all array in one loop. But, in C# we have to 
> process array 2 at a time.  This means (for the above example), we need 
> to execute the loop 4 times instead of once.

You're just going to have to rethink your design. Object-oriented design is an 
art, and has to yield to concerns of performance, stability, and expandability.

In this case, you should not encapsulate the idea of a linear or two-dimensional 
array. It looks like a good object-oriented design in theory, but makes you lose 
a lot of cache and some heap performance in practice, because, as you've said, 
you have to process one pair at a time.

It may help you to examine more of the patterns in .NET and think of more of the 
tools at your disposal. Consider this static method:

   public static double[] Sum( params double[][] args ) {
       if( args == null || args.Length == 0 )
           throw new ArgumentException( ... );

       double[] result = new double[args[0].Length];

       for( int arg = 0; arg < args.Length; arg++ )
           for( int i = 0; i < args[0].Length; i++ )
                result[i] += args[arg][i];

       return result;

It's not the best method in the world, but may get you much closer to your 
performance goal without sacrificing too much readability. Also note that the 
performance can hinge on such simple things as the order of the loops:

       for( int i = 0; i < args[0].Length; i++ )
           for( int arg = 0; arg < args.Length; arg++ )
                result[i] += args[arg][i];

The first example might perform better because it processes the arrays linearly. 
The second might perform better because the variable "result" is less likely to 
leave the processor's cache.

On top of that, remember that your two-dimensional C loop does work in C#. There 
is no rule that everything you do in C# must yield a class.

> How do we tell C# to process all operands at once, instead of only 2 at 
> a time? Do we need to modify the C# language so that it can process all 
> at once? If we do need to modify C# or the JIT compiler, where should I 
> start?

Nyet. Try first to work within your language. There are very simple things you 
can do to solve your problem without re-inventing the wheel. From what I've seen 
of your work, C# will do the job, and easily. You just haven't wrapped your head 
around the language yet.


More information about the Mono-devel-list mailing list