Reduce enumeration of rightResults in BooleanQueryExpression.IsMatch (#1155)

If Operator is Exists or leftResults is empty don't obtain rightResults,
as not relevant.

Otherwise if rightResults is not an ICollection<JToken> load it into an
List so it won't be recomputed on each enumeration of leftResults.
This commit is contained in:
Jon Hanna
2017-01-09 14:12:49 +13:00
committed by James Newton-King
parent ec2659e3ad
commit cad2ec3a09
@@ -2,6 +2,11 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Linq.JsonPath namespace Newtonsoft.Json.Linq.JsonPath
@@ -87,18 +92,22 @@ namespace Newtonsoft.Json.Linq.JsonPath
} }
public override bool IsMatch(JToken root, JToken t) public override bool IsMatch(JToken root, JToken t)
{
IEnumerable<JToken> rightResults = GetResult(root, t, Right);
IEnumerable<JToken> leftResults = GetResult(root, t, Left);
foreach (JToken leftResult in leftResults)
{ {
if (Operator == QueryOperator.Exists) if (Operator == QueryOperator.Exists)
{ {
return true; return GetResult(root, t, Left).Any();
} }
else
using (IEnumerator<JToken> leftResults = GetResult(root, t, Left).GetEnumerator())
{ {
if (leftResults.MoveNext())
{
IEnumerable<JToken> rightResultsEn = GetResult(root, t, Right);
ICollection<JToken> rightResults = rightResultsEn as ICollection<JToken> ?? rightResultsEn.ToList();
do
{
JToken leftResult = leftResults.Current;
foreach (JToken rightResult in rightResults) foreach (JToken rightResult in rightResults)
{ {
if (MatchTokens(leftResult, rightResult)) if (MatchTokens(leftResult, rightResult))
@@ -106,6 +115,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
return true; return true;
} }
} }
} while (leftResults.MoveNext());
} }
} }