Bad query performance when using a variable twice


We have a Tamino query with a poor performance and we are investigating why it’s so slow. The query is a little big, but we have been able to reduce it as much as possible still keeping the performance problem. The resulting query is something like this:

let $x := input()/A
return (count($x), count($x))

(Our original query doesn’t have two count(). This query is to show you the problem with the most simplified query)

With 20000 A documents in the database this query takes 15 seconds.

The next queries (very similar) take less than 2 seconds:

let $x := input()/A return (count($x))

let $x := input()/A return (count($x), count(input()/A))

let $x := input()/A
let $x2 := input()/A
return (count($x), count($x2))

It seems to be very sllow to do a count() on a variable that has been used before. The same performance problem appears in queries like:

let $x := input()/A
for $y in $x … (use $x in some way)
return (…, count($x))

Why these queries are that slow?
We have tried this on a Tamino