Woke up at 4am with a brainwave about improving the speed of the CodeSharing XQuery: build the queries as strings and use util:eval to run them. It took a lot of rewriting, because I now have to do much better sanitizing of inputs, but I was able to do some of that by using "castable as xs:NCName" and similar strategies, as well as regexes and quote-escaping, and I think it's good now. The eval approach works absolute wonders for speed; it's now usable on the live site.
I also found and fixed some bugs with namespace handling which were a little obscure.