I'm trying to build a high performance windows application that does basic calculations on many different data sets. Can anyone explain to me why this always returns false???
int[] x = new int[10] { 10015, 10, 9, 8, 7, 6, 5, 4, 2, 2 };
int[] y = new int[10] { 10015, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
if (x.Equals(y)) return true;
else return false;
I'm pretty sure that .Equals is comparing the ADDRESS of the two arrays, as opposed to the values. Can someone help me out on what the fastest way of comparing these arrays?? no looping is HIGHLY preferred.
Loading
AlanPosted May 13, 2008, 4:01 PM
The fastest way to compare the corresponding elements of the two arrays is to use unsafe code though, even then, you have to increment the pointers in a loop:
using System;
class Test
{
static void Main()
{
int[] x = new int[10] { 10015, 10, 9, 8, 7, 6, 5, 4, 2, 2 };
int[] y = new int[10] { 10015, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
int count = 0;
unsafe
{
fixed (int* px = x, py = y)
{
int* px2 = px, py2 = py;
while( (px2 - px) < x.Length && *px2++ == *py2++ )
{
count++;
}
}
}
if (count == x.Length)
{
Console.WriteLine("Values are the same");
}
else
{
Console.WriteLine("Values are NOT the same");
}
Console.ReadLine();
}
}
According to my rough tests, this is about 40% faster than the usual way of doing it embodied in Matthew's code.
However, unless you're doing a very large number of these comparisons, you're unlikely to see any appreciable difference in a Windows forms application where the speed (or lack of it) of the UI tends to dominate proceedings.
Matthew CochranPosted May 13, 2008, 12:11 PM
looks like your only option is to loop, but you can dump out of the loop as soon as you have found that they are not equal. Both the comparisons from the Array class seem to be comparing the address. (FYI, in your question, your arrays dont' have the same elements).
namespace ConsoleApplication2
{
class Program
{
static voidMain (string[] args)
{
int[] x = new int[10] { 10015, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
int[] y = new int[10] { 10015, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
Console.WriteLine(x.Equals(y));
Console.WriteLine(Array.Equals(x, y));
Console.WriteLine(Array.ReferenceEquals(x, y));
Console.WriteLine( x.ContentsEquivilantTo(y) );
Console.ReadLine();
}
}
static class Extension
{
public static bool ContentsEquivilantTo(this int[] a, int[] b)
{
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
if (a[i] != b[i])
return false;
return true;
}
}
}