Groovy: the best / efficient way to load dynamic scripts
I am implementing a program that uses Groovy as a scripting engine to offer users the ability to, for example, automate tasks. Hence the scripts have to be loaded on demand, which I achieve with the following code:
// short version, try/catch and error handling skipped
String[] roots = new String[] { "data" };
Binding binding = new Binding();
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
binding.setVariable("control", this.getControl());
// .. several others
gse.run(scriptName, binding); // where scriptName is provided through user selection
I noticed that execution takes 400 to 800 milliseconds for the whole block on the first run, but goes up to 200-400 on subsequent runs on my laptop.
First, for each event, a new GroovyScriptEngine was initialized and the afterword ended. In the meantime, I am using one instance of GSE for the entire program, although the initial question is not yet open:
Is there a way to precompile Groovy scripts i.e. when GSE starts up? groovyc is not an option as it would require an "external" program call.
Many thanks!
source to share
I am considering the same problem and have the following:
- Create one GSE that looks at the shared directory ("data" in your example)
- A single GSE controls and pre-compiles the items in the directory, so that's speed (not sure, but GSE seems to have some staitc element hanging around instantiation.
If your scripts don't change much, then pre-compiling them is the best way to go, and when the change is checked in, re-compiled at this time.
Hope it helps.
source to share