From a57823685babc5bbaef4f83a8658452ea28afdcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20R=C3=A4tzel?= Date: Fri, 31 May 2024 10:04:29 +0000 Subject: [PATCH] Refactor PineValue.ListValue.Equals to improve runtime efficiency Refactor to reduce stack depths and number of invocations on the most common paths taken in PineValue.ListValue.Equals --- implement/Pine.Core/PineValue.cs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/implement/Pine.Core/PineValue.cs b/implement/Pine.Core/PineValue.cs index c8fac041..832b5163 100644 --- a/implement/Pine.Core/PineValue.cs +++ b/implement/Pine.Core/PineValue.cs @@ -138,11 +138,30 @@ public virtual bool Equals(ListValue? other) if (other is null) return false; - return ReferenceEquals(this, other) - || - (slimHashCode == other.slimHashCode && - Elements.Count == other.Elements.Count && - Elements.SequenceEqual(other.Elements)); + if (ReferenceEquals(this, other)) + return true; + + if (slimHashCode != other.slimHashCode || Elements.Count != other.Elements.Count) + return false; + + for (int i = 0; i < Elements.Count; i++) + { + var selfElement = Elements[i]; + var otherElement = other.Elements[i]; + + if (selfElement is ListValue selfList && otherElement is ListValue otherList) + { + if (!selfList.Equals(otherList)) + return false; + } + else + { + if (!selfElement.Equals(otherElement)) + return false; + } + } + + return true; } public override int GetHashCode() => slimHashCode;