java集成groovy优化

来源:互联网 发布:qq邮箱smtp设置 端口 编辑:程序博客网 时间:2024/06/06 00:49

继前面一章讲到了groovy的使用方式,有loader以及engine,但是这两个方式的性能还是不能令我们满意,然后我们分析了下groovy的源码,看了下里面的实现逻辑,发现groovy在生成class文件之后(缓存class信息),在每次执行文件操作的时候都会new一个instance,这样做的意义在于engin里面使用binding参数,这样就需要每次生成实例,来产生对应的binding参数,源码如下:

try {                if (Script.class.isAssignableFrom(scriptClass)) {                    try {                        Constructor constructor = scriptClass.getConstructor(Binding.class);                        script = (Script) constructor.newInstance(context);                    } catch (NoSuchMethodException e) {                        // Fallback for non-standard "Script" classes.                        script = (Script) scriptClass.newInstance();                        script.setBinding(context);                    }                } 

所以,我这边就建立一个map来缓存实例,每次同一个文件执行的时候,先从缓存里面取,把参数通过方法的形式传到groovy里面,这样就减少了创建实例的时间,同时也减少了gc的次数,缓存代码如下:

public static Script createScript(String scriptName,GroovyScriptEngine engine,Binding binding) throws ResourceException, ScriptException {        if (scriptMap.containsKey(scriptName)) {            return scriptMap.get(scriptName);        } else {            Script script = engine.createScript(scriptName, binding);            scriptMap.put(scriptName,script);            return script;        }    }
性能如下:

效果还是很明显的

0 0
原创粉丝点击