Skip to content

Commit 47012be

Browse files
committed
Optimize DistinctRootEntityResultTransformer
1 parent 116398d commit 47012be

File tree

1 file changed

+15
-23
lines changed

1 file changed

+15
-23
lines changed

src/NHibernate/Transform/DistinctRootEntityResultTransformer.cs

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -12,24 +12,16 @@ public class DistinctRootEntityResultTransformer : IResultTransformer, ITupleSub
1212
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DistinctRootEntityResultTransformer));
1313
private static readonly object Hasher = new object();
1414

15-
internal sealed class Identity
15+
internal sealed class IdentityComparer : IEqualityComparer<object>
1616
{
17-
internal readonly object entity;
18-
19-
internal Identity(object entity)
20-
{
21-
this.entity = entity;
22-
}
23-
24-
public override bool Equals(object other)
17+
public new bool Equals(object x, object y)
2518
{
26-
Identity that = (Identity) other;
27-
return ReferenceEquals(entity, that.entity);
19+
return ReferenceEquals(x, y);
2820
}
2921

30-
public override int GetHashCode()
22+
public int GetHashCode(object obj)
3123
{
32-
return RuntimeHelpers.GetHashCode(entity);
24+
return RuntimeHelpers.GetHashCode(obj);
3325
}
3426
}
3527

@@ -40,13 +32,16 @@ public object TransformTuple(object[] tuple, string[] aliases)
4032

4133
public IList TransformList(IList list)
4234
{
43-
IList result = (IList)Activator.CreateInstance(list.GetType());
44-
var distinct = new HashSet<Identity>();
35+
if (list.Count < 2)
36+
return list;
37+
38+
IList result = (IList) Activator.CreateInstance(list.GetType());
39+
var distinct = new HashSet<object>(new IdentityComparer());
4540

4641
for (int i = 0; i < list.Count; i++)
4742
{
4843
object entity = list[i];
49-
if (distinct.Add(new Identity(entity)))
44+
if (distinct.Add(entity))
5045
{
5146
result.Add(entity);
5247
}
@@ -77,13 +72,10 @@ public bool IsTransformedValueATupleElement(String[] aliases, int tupleLength)
7772

7873
public override bool Equals(object obj)
7974
{
80-
if (obj == null || obj.GetHashCode() != Hasher.GetHashCode())
81-
{
82-
return false;
83-
}
84-
// NH-3957: do not rely on hashcode alone.
85-
// Must be the exact same type
86-
return obj.GetType() == typeof(DistinctRootEntityResultTransformer);
75+
if (ReferenceEquals(obj, this))
76+
return true;
77+
78+
return obj is DistinctRootEntityResultTransformer;
8779
}
8880

8981
public override int GetHashCode()

0 commit comments

Comments
 (0)