[Mono-dev] Jagged arrays over multidimensional arrays

Stifu stifu at free.fr
Tue Mar 24 10:53:52 EDT 2009


Microsoft (through MSDN and FxCop) recommends using jagged arrays
(likeThis[][]) over multidimensional arrays(likeThat[,]), because they're
usually faster, basically (especially if the sub arrays in your jagged array
don't all have the same size). See:
http://msdn.microsoft.com/en-us/library/ms182277.aspx

I made a simple test program that initializes arrays to check the speed
difference, and I could see that with a simple initialization loop, jagged
arrays were indeed a bit faster than multidimensional ones (even if all sub
arrays in the jagged array have the same size, as with a multidimensional
one).

But before changing all the multidimensional arrays to jagged arrays in my
application, I thought I'd check Mono... with which jagged arrays are slower
than multidimensional ones, unlike with .NET.

Is it worth filing a bug report for a performance issue like this one?

For more details on the way .NET generates code for jagged and
multidimensional arrays:
http://www.guidanceshare.com/wiki/.NET_2.0_Performance_Guidelines_-_Arrays#Use_Jagged_Arrays_Instead_of_Multidimensional_Arrays

About the tests I ran on my computer:

.NET (2.0) results:
Multidimensional arrays: 02.89 seconds
Jagged arrays: 02.74 seconds

Mono (2.4 RC3) results:
Multidimensional arrays: 04.57 seconds
Jagged arrays: 04.94 seconds

And here's the test program (feel free to raise the "iterations" value, I
set it to only 3000 because my computer is quite old):

using System;
using System.Windows.Forms;

namespace Arrays
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
			
			int iterations = 3000;
			
			DateTime start = DateTime.Now;
			for(int i = 0; i < iterations; i++)
			{
				int[,] multiDimensionalArray = new int[128, 128];
				
				for(int y = 0; y < 128; y++)
				{
					for(int x = 0; x < 128; x++)
					{
						multiDimensionalArray[y, x] = 5;
					}
				}
			}
			TimeSpan duration = DateTime.Now - start;
			
			start = DateTime.Now;
			for(int i = 0; i < iterations; i++)
			{
				int[][] jaggedArray = new int[128][];
				
				for(int y = 0; y < 128; y++)
				{
					jaggedArray[y] = new int[128];
					
					for(int x = 0; x < 128; x++)
					{
						jaggedArray[y][x] = 5;
					}
				}
			}
			TimeSpan duration2 = DateTime.Now - start;
			
			MessageBox.Show(String.Format(
				"Multidimensional array : {0}\n" +
				"Jagged array : {1}",
				duration.ToString(),
				duration2.ToString()));
		}
	}
}
-- 
View this message in context: http://www.nabble.com/Jagged-arrays-over-multidimensional-arrays-tp22682187p22682187.html
Sent from the Mono - Dev mailing list archive at Nabble.com.



More information about the Mono-devel-list mailing list