jastrachan | 15 May 09:39 2004

Re: [groovy-dev] Optimizing Scripts (just an Idea)

On 14 May 2004, at 11:58, Thomas Heller wrote:
> Bing, thanks for the example that helps alot.
> jastrachan@... wrote:
>> Great idea Thomas.
>> The main reason that Scripts have used a binding for all their 
>> variables, up to now, is that folks executing arbitrary expressions, 
>> command line tools, BSF integration and the like are used to working 
>> like this. i.e. you setup some state outside of the script, run the 
>> script, then look at the state again later.
> What I wanted to say is how we can optimize the binding. I _want_ to 
> use the binding. I want to setup state outside and then make my script 
> use it. I want the script to modify state. An example:
> Binding binding = new Binding();
> binding.setVariable("service", pico.getComponentInstance("myService"));
> binding.setVariable("state", new SomeState());
> GroovyShell shell = new GroovyShell(binding);
> shell.run("/test.groovy");
> SomeState state = (SomeState)binding.getVariable("state");
> This is exactly how I want to do it and theres nothing that should be 
> changed about it. However my optimization (which I hope it is gonna 
> test it tommorrow) works with this and it will let you work with state 
> just fine.
> The whole idea was to reduce the amount of Map lookups when I use a 
> variable inside a script.
> For example
> println(x);
> println(x);
> println(x);
> inside a script is 3 map lookups. If done my way its 1 map lookup and 
> 3 local var references. Should be faster, I'm gonna test it.

Aha! I'm with you now. Great idea!

Just be a little careful of a variable name being reused inside 2 
scopes with different types etc.

for (x in 0..10) {
     Integer y = 123

for (x in 0..10) {
     String y = "hello"

>> Maybe we need some kind of flag in the CompilerConfig or GroovyShell 
>> or whatnot to allow enable/disable of binding value exports? We could 
>> always disable exporting of variables by default but provide the user 
>> with a way to export values to the caller.
>> e.g.
>> x = 123 // local variable
>> binding.y = 456 // output this to the binding I was passed
> I think when we just use local class variables inside scripts and make
> use of some "binding/runtime/global" export it would actually help 
> alot.
> Usually when I pass variables from the outside into the script the 
> script will know about it and expect it. So when I write binding.abc 
> its clear that its an external parameter. Same for the output I can 
> see in the script that I can expect an returning variable abc when I 
> do binding.abc = 123;

Good point. Maybe we should make exporting explicit.

Also folks could return things from a script - essentially make their 
own bindings.

answer = [:]
answer.x = 123
answer.y = "hello"
return answer