From 5aa75ae595927b81efa486cceff73f0f1c14e364 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 28 Mar 2016 19:44:05 +1300 Subject: [PATCH] -Reduced allocations of JToken.Path++ --- Src/Newtonsoft.Json/Linq/JToken.cs | 49 +++++++++++------------------- 1 file changed, 18 insertions(+), 31 deletions(-) diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index bac89342..df753af1 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -190,45 +190,32 @@ namespace Newtonsoft.Json.Linq return string.Empty; } - List ancestors = new List(); + List positions = new List(); + JToken previous = null; for (JToken current = this; current != null; current = current.Parent) { - ancestors.Add(current); - } - ancestors.Reverse(); - - List positions = new List(ancestors.Count); - for (int i = 0; i < ancestors.Count; i++) - { - JToken current = ancestors[i]; - JToken next = null; - if (i + 1 < ancestors.Count) + switch (current.Type) { - next = ancestors[i + 1]; - } - else if (ancestors[i].Type == JTokenType.Property) - { - next = ancestors[i]; - } - - if (next != null) - { - switch (current.Type) - { - case JTokenType.Property: - JProperty property = (JProperty)current; - positions.Add(new JsonPosition(JsonContainerType.Object) { PropertyName = property.Name }); - break; - case JTokenType.Array: - case JTokenType.Constructor: - int index = ((IList)current).IndexOf(next); + case JTokenType.Property: + JProperty property = (JProperty)current; + positions.Add(new JsonPosition(JsonContainerType.Object) { PropertyName = property.Name }); + break; + case JTokenType.Array: + case JTokenType.Constructor: + if (previous != null) + { + int index = ((IList)current).IndexOf(previous); positions.Add(new JsonPosition(JsonContainerType.Array) { Position = index }); - break; - } + } + break; } + + previous = current; } + positions.Reverse(); + return JsonPosition.BuildPath(positions, null); } }