From 9929056d310e4a913eb7f82525cd181f68125f26 Mon Sep 17 00:00:00 2001 From: kyri-petrou <67301607+kyri-petrou@users.noreply.github.com> Date: Sat, 24 Aug 2024 13:17:36 +0300 Subject: [PATCH] Optimize `Field#allFieldsUniqueNameAndCondition` (#2368) * Optimize `Field#allFieldsUniqueNameAndCondition` * PR comment * Use local `nil` --- .../main/scala/caliban/execution/Field.scala | 31 +++++++++---------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/core/src/main/scala/caliban/execution/Field.scala b/core/src/main/scala/caliban/execution/Field.scala index f8e03d705..c2c09284a 100644 --- a/core/src/main/scala/caliban/execution/Field.scala +++ b/core/src/main/scala/caliban/execution/Field.scala @@ -46,25 +46,22 @@ case class Field( private[caliban] val aliasedName: String = if (alias.isEmpty) name else alias.get - private[caliban] lazy val allFieldsUniqueNameAndCondition: Boolean = { - def inner(fields: List[Field]): Boolean = { - val headCondition = fields.head._condition - - val seen = new mutable.HashSet[String] - seen.add(fields.head.aliasedName) - - var rem = fields.tail - while (rem ne Nil) { - val f = rem.head - val continue = seen.add(f.aliasedName) && f._condition == headCondition - if (!continue) return false + // TODO: Change the name to `allConditionsUnique` in the next minor version + private[caliban] def allFieldsUniqueNameAndCondition: Boolean = + fields.isEmpty || fields.tail.isEmpty || allConditionsUniqueLazy + + private lazy val allConditionsUniqueLazy: Boolean = { + val headCondition = fields.head._condition + var rem = fields.tail + var res = true + val nil = Nil + while ((rem ne nil) && res) { + val f = rem.head + if (f._condition == headCondition) rem = rem.tail - } - true + else res = false } - - val fields0 = fields - fields0.isEmpty || fields0.tail.isEmpty || inner(fields0) + res } def combine(other: Field): Field =