I have two XQueries that do exactly the same thing, i.e. create a
list of
waters in the Facts database and display where these waters flow
into, if any.
But Query 1 executes 10 times faster than Query 2 (in the GUI).
The only difference is in the selection of the query context.
Query 1 assumes the Facts database is open and does not use an
explicit doc()
or collection() context.
Query 2 uses an explicit collection("Facts") context
Query 1 executes in appr. 600 msecs, Query 2 in appr. 60 msecs (!)
How can there be such a huge difference? Is it because Query 2
operates twice
on the $facts variable and does not need to evaluate that again?
Listings:
Query1
(: list waters and where they stream to (if any):)
for $source in //(sea|river|lake)
let $toId := $source/to/@water
let $to := (//sea|//river|//lake)[@id=$toId][1]
let $name := if (empty($to/local-name())) then "none" else
$to/local-name()
return
element water {
element {$source/local-name()} {data($source/@name)},
if (not($name="none"))then
element streamsTo {
attribute {$name} {data($to/@name)}
}
else ()
}
Query2
(: list waters and where they stream to (if any):)
let $facts := collection("Facts")//(sea|river|lake )
for $source in $facts
let $toId := $source/to/@water
let $to := $facts[@id=$toId][1]
let $name := if (empty($to/local-name())) then "none" else
$to/local-name()
return
element water {
element {$source/local-name()} {data($source/@name)},
if (not($name="none"))then
element streamsTo {
attribute {$name} {data($to/@name)}
}
else ()
}
As a side-question: I want to extend the query to make it
recursive: river "Bahr
el-Djebel" streams into river "White Nile" streams into river
"Nile"
streams into sea "Mediterranean Sea"
I think I can find out how to do that, but how can I optimize the
recursion
process? Would a recursive function be efficient?