Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit eb2d44e

Browse files
mountgellertjkotas
authored andcommitted
Fixing Delegate's hash code's distribution (#11019)
Delegate's GetHashCode just returns the hash code of the delegate type. For a scenario where delegates are used as keys in a dictionary, this leads to obvious performance problems. We should look at coming up with a better GetHashCode that properly factors in the target object and method, in all of the various forms a delegate can take.
1 parent 171a52d commit eb2d44e

File tree

2 files changed

+6
-3
lines changed

2 files changed

+6
-3
lines changed

src/mscorlib/src/System/Delegate.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,10 @@ public override int GetHashCode()
179179
else
180180
return unchecked((int)((long)this._methodPtrAux));
181181
*/
182-
return GetType().GetHashCode();
182+
if (_methodPtrAux.IsNull())
183+
return ( _target != null ? RuntimeHelpers.GetHashCode(_target) * 33 : 0) + GetType().GetHashCode();
184+
else
185+
return GetType().GetHashCode();
183186
}
184187

185188
public static Delegate Combine(Delegate a, Delegate b)

tests/src/CoreMangLib/cti/system/delegate/delegategethashcode1.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,15 +218,15 @@ public bool PosTest7()
218218
{
219219
bool retVal = true;
220220

221-
TestLibrary.TestFramework.BeginScenario("PosTest7: Use the different instance's same instance method to create two delegate which delegate object is the same,their hashcode is equal");
221+
TestLibrary.TestFramework.BeginScenario("PosTest7: Use the different instance's same instance method to create two delegate which delegate object is the same, their hashcode is different");
222222

223223
try
224224
{
225225
DelegateGetHashCode delctor = new DelegateGetHashCode();
226226
booldelegate workDelegate = new booldelegate(new TestClass(1).StartWork_Bool);
227227
booldelegate workDelegate1 = new booldelegate(new TestClass1(2).StartWork_Bool );
228228

229-
if (workDelegate.GetHashCode()!=workDelegate1.GetHashCode())
229+
if (workDelegate.GetHashCode()==workDelegate1.GetHashCode())
230230
{
231231
TestLibrary.TestFramework.LogError("013", "HashCode is not excepted ");
232232
retVal = false;

0 commit comments

Comments
 (0)