From 2a244bbbe0163d23562b0984b104a3b4031dbee0 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 11 Mar 2016 06:54:15 +0800 Subject: [PATCH] Explicit AnimationStateData key in C#. From user issue: http://esotericsoftware.com/forum/Performance-issue-of-KeyValuePair-5966 --- spine-csharp/src/AnimationStateData.cs | 31 +++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/spine-csharp/src/AnimationStateData.cs b/spine-csharp/src/AnimationStateData.cs index eea87429e..bf36b2c55 100644 --- a/spine-csharp/src/AnimationStateData.cs +++ b/spine-csharp/src/AnimationStateData.cs @@ -35,7 +35,7 @@ using System.Collections.Generic; namespace Spine { public class AnimationStateData { internal SkeletonData skeletonData; - private Dictionary, float> animationToMixTime = new Dictionary, float>(); + private Dictionary animationToMixTime = new Dictionary(AnimationPairComparer.Instance); internal float defaultMix; public SkeletonData SkeletonData { get { return skeletonData; } } @@ -56,16 +56,41 @@ namespace Spine { public void SetMix (Animation from, Animation to, float duration) { if (from == null) throw new ArgumentNullException("from cannot be null."); if (to == null) throw new ArgumentNullException("to cannot be null."); - KeyValuePair key = new KeyValuePair(from, to); + AnimationPair key = new AnimationPair(from, to); animationToMixTime.Remove(key); animationToMixTime.Add(key, duration); } public float GetMix (Animation from, Animation to) { - KeyValuePair key = new KeyValuePair(from, to); + AnimationPair key = new AnimationPair(from, to); float duration; if (animationToMixTime.TryGetValue(key, out duration)) return duration; return defaultMix; } + + struct AnimationPair { + public readonly Animation a1; + public readonly Animation a2; + + public AnimationPair (Animation a1, Animation a2) { + this.a1 = a1; + this.a2 = a2; + } + } + + // Avoids boxing in the dictionary. + class AnimationPairComparer : IEqualityComparer { + internal static readonly AnimationPairComparer Instance = new AnimationPairComparer(); + + bool IEqualityComparer.Equals (AnimationPair x, AnimationPair y) { + return ReferenceEquals(x.a1, y.a1) && ReferenceEquals(x.a2, y.a2); + } + + int IEqualityComparer.GetHashCode (AnimationPair obj) { + // from Tuple.CombineHashCodes // return (((h1 << 5) + h1) ^ h2); + int h1 = obj.a1.GetHashCode(); + return (((h1 << 5) + h1) ^ obj.a2.GetHashCode()); + } + } } }