ソースコード
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using Unity.PerformanceTesting;
public sealed class DictionaryStructKeyTest
{
[SuppressMessage( "ReSharper", "NotAccessedField.Local" )]
private readonly struct KeyStruct1
{
private readonly int m_primaryId;
private readonly int m_secondaryId;
public KeyStruct1( int primaryId, int secondaryId )
{
m_primaryId = primaryId;
m_secondaryId = secondaryId;
}
}
private readonly struct KeyStruct2 : IEquatable<KeyStruct2>
{
private readonly int m_primaryId;
private readonly int m_secondaryId;
public KeyStruct2( int primaryId, int secondaryId )
{
m_primaryId = primaryId;
m_secondaryId = secondaryId;
}
public bool Equals( KeyStruct2 other )
{
return m_primaryId == other.m_primaryId &&
m_secondaryId == other.m_secondaryId;
}
}
private readonly struct KeyStruct3 : IEquatable<KeyStruct3>
{
private readonly int m_primaryId;
private readonly int m_secondaryId;
public KeyStruct3( int primaryId, int secondaryId )
{
m_primaryId = primaryId;
m_secondaryId = secondaryId;
}
public bool Equals( KeyStruct3 other )
{
return m_primaryId == other.m_primaryId &&
m_secondaryId == other.m_secondaryId;
}
public override bool Equals( object obj )
{
return obj is KeyStruct3 other && Equals( other );
}
public override int GetHashCode()
{
return HashCode.Combine( m_primaryId, m_secondaryId );
}
}
[Test]
[Performance]
public void TupleTest()
{
var dictionary = new Dictionary<(int, int), string>();
var key = ( 1, 2 );
dictionary[ key ] = "";
Run( () => dictionary.GetValueOrDefault( key ) );
}
[Test]
[Performance]
public void StructTest1()
{
var dictionary = new Dictionary<KeyStruct1, string>();
var key = new KeyStruct1( 1, 2 );
dictionary[ key ] = "";
Run( () => dictionary.GetValueOrDefault( key ) );
}
[Test]
[Performance]
public void StructTest2()
{
var dictionary = new Dictionary<KeyStruct2, string>();
var key = new KeyStruct2( 1, 2 );
dictionary[ key ] = "";
Run( () => dictionary.GetValueOrDefault( key ) );
}
[Test]
[Performance]
public void StructTest3()
{
var dictionary = new Dictionary<KeyStruct3, string>();
var key = new KeyStruct3( 1, 2 );
dictionary[ key ] = "";
Run( () => dictionary.GetValueOrDefault( key ) );
}
private static void Run( Action action )
{
const int warmupCount = 10;
const int measurementCount = 100;
const int iterationsPerMeasurement = 100000;
Measure
.Method( action )
.WarmupCount( warmupCount )
.MeasurementCount( measurementCount )
.IterationsPerMeasurement( iterationsPerMeasurement )
.GC()
.Run()
;
}
}
測定結果
タプル
通常の構造体
IEquatable インターフェイスを実装した構造体
IEquatable インターフェイスを実装して Equals メソッドと GetHashCode メソッドをオーバーライドした構造体
検証環境