Skip to content

Commit d402836

Browse files
authored
Improve GetCommonBase method performance (#93)
1 parent 88c223c commit d402836

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed

Orm/Xtensive.Orm/Modelling/Comparison/Comparer.cs

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -735,33 +735,33 @@ private bool TryRegisterDifference(object source, object target, Difference diff
735735
/// <returns>The highest common base type.</returns>
736736
protected static Type GetCommonBase(object source, object target)
737737
{
738-
var sourceAncestors = GetAncestors(source==null ? WellKnownTypes.Object : source.GetType());
739-
var targetAncestors = GetAncestors(target==null ? WellKnownTypes.Object : target.GetType());
740-
var sourceType = sourceAncestors[sourceAncestors.Count - 1];
741-
var targetType = targetAncestors[targetAncestors.Count - 1];
742-
if (sourceType.IsAssignableFrom(targetType))
738+
var sourceType = source?.GetType() ?? WellKnownTypes.Object;
739+
var targetType = target?.GetType() ?? WellKnownTypes.Object;
740+
741+
if (sourceType.IsAssignableFrom(targetType)) {
743742
return targetType;
744-
if (targetType.IsAssignableFrom(sourceType))
743+
}
744+
745+
if (targetType.IsAssignableFrom(sourceType)) {
745746
return sourceType;
746-
var commonBase = WellKnownTypes.Object;
747-
for (int i = 0; i < Math.Min(sourceAncestors.Count, targetAncestors.Count); i++) {
748-
var ancestor = sourceAncestors[i];
749-
if (ancestor!=targetAncestors[i])
750-
break;
751-
commonBase = ancestor;
752747
}
753-
return commonBase;
748+
749+
var sourceAncestors = GetAncestors(sourceType).ToHashSet();
750+
foreach (var ancestorType in GetAncestors(targetType)) {
751+
if (sourceAncestors.Contains(ancestorType)) {
752+
return ancestorType;
753+
}
754+
}
755+
756+
return WellKnownTypes.Object;
754757
}
755758

756-
private static List<Type> GetAncestors(Type type)
759+
private static IEnumerable<Type> GetAncestors(Type type)
757760
{
758-
var list = new List<Type>();
759-
while (type!=WellKnownTypes.Object) {
760-
list.Insert(0, type);
761+
while (type != null) {
762+
yield return type;
761763
type = type.BaseType;
762764
}
763-
list.Insert(0, WellKnownTypes.Object);
764-
return list;
765765
}
766766

767767
#endregion

0 commit comments

Comments
 (0)