问题
I'm trying to improve the performance of a javascript snippet evaluator. These script snippets can reference any number of variables that exist in a string-keyed map of json-like object graphs (IE: Json AST). I'm using JDK 1.6 and the embedded Rhinoscript engine (v1.6R2).
Currently, processing takes the form:
- Snippet is parsed to discover the names of referenced variables
- Variables are retrieved from the map and serialized to a json string
- Json string is assigned to a similarly named variable at the start of the script
- Evaluate augmented script
I'm trying to figure out how to skip the json serializing stage and create direct Rhinoscript native objects to place in the 'bindings' for the script. The desired steps would then be:
- Snippet is parsed to discover the names of referenced variables
- Variables are retrieved from the map and converted to native Rhinoscript equivalents
- Native objects are placed in bindings
- Evaluation of original script with said bindings
Do you know where I could find documentation or examples of how to instantiate native rhinoscript objects?
My scala learning project might be of some use if you want to tinker. And any answer I come up with should appear there too...
http://subversion.assembla.com/svn/freshcode_public/learn_scala/datastore/src/test/scala/pkg/script
Thanks in advance.
回答1:
So after much fiddling I've come up with an adequate solution although it did not yield the performance increase I had hoped for (only 10% faster).
The solution is specific to Scala / Lift / Json and is contained in the ScriptingUtil.scala file.
To summarise:
- Context.javaToJs() does not seem to work in all cases. (
java.lang.RuntimeException: No Context associated with current Thread
) - A 'scope' object of type
Scriptable
is needed. The solution I came up with isn't pretty but it works. To create a NativeArray:
val na = new NativeArray(arr) na.setPrototype(ScriptableObject.getClassPrototype(scope, "Array"))
来源:https://stackoverflow.com/questions/8558405/instantiating-rhinoscript-native-objects-from-java-scala