Pramod Almeti
Pramod Almeti

Reputation: 13

C# Cache Saxon Compiler and Executable objects

Using below code to run Evaluations using SaxonCA API

Task newTask = Task.Run(() =>
{
    Processor processor = new Processor();
    DocumentBuilder documentBuilder = processor.NewDocumentBuilder();
    documentBuilder.IsLineNumbering = true;
    documentBuilder.WhitespacePolicy = WhitespacePolicy.PreserveAll;
    XQueryCompiler compiler = processor.NewXQueryCompiler();
    string query = BuildXqueryString();

    if (!String.IsNullOrEmpty(query))
    {
        XQueryExecutable executable = compiler.Compile(query);
        XQueryEvaluator evaluator = executable.Load();
        evaluator.ContextItem = documentBuilder.Build(xmlNode);
        var evaluations = evaluator.Evaluate();
    }
}

Queries (Xquery) are constant and never change until there is new build. Above code is run parallel for different documents. Wanted to check if there is any way to Cache the compiler/evaluator object to avoid query compilations for every document we process.

Any help would be appreciated.

Upvotes: 0

Views: 125

Answers (1)

Michael Kay
Michael Kay

Reputation: 163468

The XQueryExecutable is immutable and thread-safe, so you can safely cache it: for example by keeping a (thread-safe) map or hash table from the query string to the XQueryExecutable. The only caveat is that you will have to change the way you instantiate the Processor object: rather than creating a new Processor every time you run a query, you should have a single Processor object for the entire application, because the compiled query and the source document must be built under the control of the same Processor.

The XQueryCompiler is serially re-usable, but since the ErrorList object is updated during the course of a compilation, it shouldn't be used in more than one thread concurrently. So you may find it simplest to create a new XQueryCompiler every time you compile a query.

Upvotes: 1

Related Questions