From 678038470e0a20f2702603f72a347cb66f4e817a Mon Sep 17 00:00:00 2001 From: Dariusz Komosinski Date: Sat, 16 Nov 2019 21:53:05 +0100 Subject: [PATCH 1/2] Optimize FontFamily and members hashcode/equality. --- src/Avalonia.Visuals/Media/FontFamily.cs | 27 +++++---------- .../Media/Fonts/FamilyNameCollection.cs | 34 +++++++++++++++++-- 2 files changed, 40 insertions(+), 21 deletions(-) diff --git a/src/Avalonia.Visuals/Media/FontFamily.cs b/src/Avalonia.Visuals/Media/FontFamily.cs index b57b4a0ca8..efb3c99143 100644 --- a/src/Avalonia.Visuals/Media/FontFamily.cs +++ b/src/Avalonia.Visuals/Media/FontFamily.cs @@ -184,36 +184,25 @@ namespace Avalonia.Media { unchecked { - var hash = (int)2186146271; - - if (Key != null) - { - hash = (hash * 15768619) ^ Key.GetHashCode(); - } - else - { - hash = (hash * 15768619) ^ FamilyNames.GetHashCode(); - } - - if (Key != null) - { - hash = (hash * 15768619) ^ Key.GetHashCode(); - } - - return hash; + return ((FamilyNames != null ? FamilyNames.GetHashCode() : 0) * 397) ^ (Key != null ? Key.GetHashCode() : 0); } } public override bool Equals(object obj) { + if (ReferenceEquals(this, obj)) + { + return true; + } + if (!(obj is FontFamily other)) { return false; } - if (Key != null) + if (Key != other.Key) { - return other.FamilyNames.Equals(FamilyNames) && other.Key.Equals(Key); + return false; } return other.FamilyNames.Equals(FamilyNames); diff --git a/src/Avalonia.Visuals/Media/Fonts/FamilyNameCollection.cs b/src/Avalonia.Visuals/Media/Fonts/FamilyNameCollection.cs index e777d93315..eb0faf4187 100644 --- a/src/Avalonia.Visuals/Media/Fonts/FamilyNameCollection.cs +++ b/src/Avalonia.Visuals/Media/Fonts/FamilyNameCollection.cs @@ -111,7 +111,24 @@ namespace Avalonia.Media.Fonts /// public override int GetHashCode() { - return ToString().GetHashCode(); + if (Count == 0) + { + return 0; + } + + unchecked + { + int hash = 17; + + for (var i = 0; i < Names.Count; i++) + { + string name = Names[i]; + + hash = hash * 23 + name.GetHashCode(); + } + + return hash; + } } /// @@ -128,7 +145,20 @@ namespace Avalonia.Media.Fonts return false; } - return other.ToString().Equals(ToString()); + if (other.Count != Count) + { + return false; + } + + for (int i = 0; i < Count; i++) + { + if (Names[i] != other.Names[i]) + { + return false; + } + } + + return true; } public int Count => Names.Count; From 364d6697cc5bef0a7fe2f8a8b5e938f0fa9644d9 Mon Sep 17 00:00:00 2001 From: Dariusz Komosinski Date: Sat, 16 Nov 2019 22:33:32 +0100 Subject: [PATCH 2/2] Fix wrath of equality operator. --- src/Avalonia.Visuals/Media/FontFamily.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Avalonia.Visuals/Media/FontFamily.cs b/src/Avalonia.Visuals/Media/FontFamily.cs index efb3c99143..771de524d9 100644 --- a/src/Avalonia.Visuals/Media/FontFamily.cs +++ b/src/Avalonia.Visuals/Media/FontFamily.cs @@ -200,7 +200,7 @@ namespace Avalonia.Media return false; } - if (Key != other.Key) + if (!Equals(Key, other.Key)) { return false; }