C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The variable array1 was determined not to be equal to array2. But Array1 was equal to array3.
And: Array1 was equal to array4 when the IEqualityComparer implementation (StringComparer.OrdinalIgnoreCase) was specified.
StringComparison, StringComparerOrdinalIgnoreCase: This causes the elements to be equal if they only have different cases. The character casing is ignored.
C# program that uses SequenceEqual
using System;
using System.Linq;
class Program
{
static void Main()
{
string[] array1 = { "dot", "net", "Codex" };
string[] array2 = { "a", "different", "array" };
string[] array3 = { "dot", "net", "Codex" };
string[] array4 = { "DOT", "NET", "PERLS" };
bool a = array1.SequenceEqual(array2);
bool b = array1.SequenceEqual(array3);
bool c = array1.SequenceEqual(array4, StringComparer.OrdinalIgnoreCase);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
}
Output
False
True
True
Version 1: This version of the code uses SequenceEqual to compare 2 larger-sized integer arrays.
Int ArrayVersion 2: Here we use a for-loop method called ArraysEqual to compare the arrays.
ForResult: SequenceEqual was more than ten times slower than the imperative algorithm (ArraysEqual).
Note: It's good to keep in mind that SequenceEqual on large equal arrays is more than ten times slower than a loop.
C# program that benchmarks SequenceEqual
using System;
using System.Diagnostics;
using System.Linq;
class Program
{
static void Main()
{
const int max = 10000;
var a1 = Enumerable.Range(0, short.MaxValue).ToArray();
var a2 = Enumerable.Range(0, short.MaxValue).ToArray();
var s1 = Stopwatch.StartNew();
// Version 1: use SequenceEqual.
for (int i = 0; i < max; i++)
{
bool equals = a1.SequenceEqual(a2);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use custom method.
for (int i = 0; i < max; i++)
{
bool equals = ArraysEqual(a1, a2);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
max).ToString("0.00 ns"));
Console.Read();
}
static bool ArraysEqual(int[] a1, int[] a2)
{
if (a1.Length == a2.Length)
{
for (int i = 0; i < a1.Length; i++)
{
if (a1[i] != a2[i])
{
return false;
}
}
return true;
}
return false;
}
}
Output
515889.45 ns
36280.79 ns