Created
October 13, 2022 14:38
-
-
Save MisterKidX/89057b359f6f3828257c56ec56b17ae5 to your computer and use it in GitHub Desktop.
Default equality comparison of the C# language
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.Generic; | |
using System.Diagnostics; | |
int iterations = 1_000_000; | |
List<ReflectionComparison> comparisons1 = new List<ReflectionComparison>(); | |
List<ReflectionComparison> comparisons2 = new List<ReflectionComparison>(); | |
List<ByteComparison> comparisons3 = new List<ByteComparison>(); | |
List<ByteComparison> comparisons4 = new List<ByteComparison>(); | |
List<ReferenceType> comparisons5 = new List<ReferenceType>(); | |
List<ReferenceType> comparisons6 = new List<ReferenceType>(); | |
for (int i = 0; i < iterations; i++) | |
{ | |
comparisons1.Add(new ReflectionComparison()); | |
comparisons2.Add(new ReflectionComparison()); | |
comparisons3.Add(new ByteComparison()); | |
comparisons4.Add(new ByteComparison()); | |
comparisons5.Add(new ReferenceType()); | |
comparisons6.Add(new ReferenceType()); | |
} | |
Stopwatch stp = Stopwatch.StartNew(); | |
var b = false; | |
// performs reflection to test for equality (O(n)) | |
for (int i = 0; i < iterations; i++) | |
{ | |
b = comparisons1[i].Equals(comparisons2[i]); | |
} | |
Console.WriteLine("ReflectionComparison => " + stp.ElapsedMilliseconds); | |
stp.Restart(); | |
// performs a byte-by-byte comparison. happens because it doesn't have a reference type in its fields. (O(n)) | |
for (int i = 0; i < iterations; i++) | |
{ | |
b = comparisons3[i].Equals(comparisons4[i]); | |
} | |
Console.WriteLine("Byte Comparisons => " + stp.ElapsedMilliseconds); | |
stp.Restart(); | |
// performs a reference comparison (O(1)) | |
for (int i = 0; i < iterations; i++) | |
{ | |
b = comparisons5[i].Equals(comparisons6[i]); | |
} | |
Console.WriteLine("Refernce Comparison => " + stp.ElapsedMilliseconds); | |
stp.Restart(); | |
class ReferenceType | |
{ | |
public int X; | |
public int Y; | |
} | |
struct ByteComparison | |
{ | |
public int X; | |
public int Y; | |
} | |
struct ReflectionComparison | |
{ | |
public int X; | |
public int Y; | |
public ReferenceType ReferenceType; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment