Skip to content

Instantly share code, notes, and snippets.

@BurstX
Last active December 16, 2021 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BurstX/7d48f5fb4fd47224b2bab33e0f244ebe to your computer and use it in GitHub Desktop.
Save BurstX/7d48f5fb4fd47224b2bab33e0f244ebe to your computer and use it in GitHub Desktop.
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