Last active
December 16, 2021 11:24
-
-
Save BurstX/7d48f5fb4fd47224b2bab33e0f244ebe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Security.Cryptography; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace MyBenchmarks | |
{ | |
public class CompareArraysBenchmark | |
{ | |
private const int N = 10000; | |
private readonly int[] a1 = new int[N], a2 = new int[N]; | |
private readonly Random r = new Random(); | |
public CompareArraysBenchmark() | |
{ | |
for(int i = 0; i < N; i++) | |
{ | |
a1[i] = r.Next(N); | |
a2[i] = r.Next(N); | |
} | |
} | |
[Benchmark] | |
public bool CompareArraysWithFor() | |
{ | |
return ByteArraysEqual(a1, a2); | |
} | |
[Benchmark] | |
public bool CompareArraysWithStructuralEquatability() | |
{ | |
return StructuralComparisons.StructuralEqualityComparer.Equals((IStructuralEquatable)a1, (IStructuralEquatable)a2); | |
} | |
[Benchmark] | |
public bool CompareArraysWithStructuralEquatability2() | |
{ | |
return ((IStructuralEquatable)a1).Equals((IStructuralEquatable)a2, EqualityComparer<int>.Default); | |
} | |
[Benchmark] | |
public bool CompareArraysWithSequenceEqual() | |
{ | |
return a1 != null && a2 != null && a1.SequenceEqual(a2); | |
} | |
private static bool ByteArraysEqual(int[] a1, int[] a2) | |
{ | |
if (a1 == a2 && a1 != null) | |
return true; | |
if (a1 == null || a2 == null || a1.Length != a2.Length) | |
return false; | |
for (int i = 0; i < a1.Length; i++) | |
if (a1[i] != a2[i]) | |
return false; | |
return true; | |
} | |
} | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<CompareArraysBenchmark>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment