我正在使用 Groovy 执行一些 Java 代码。就我的目的而言,Groovy 很容易使用,因为我必须执行的代码具有我无法预测的任意数量的参数,因为它取决于用户输入。我所说的输入是 OWL 公理,它们是嵌套的。这是我的代码:
//The reflection
static void reflectionToOwl() {
Binding binding = new Binding(); //155 ms
GroovyShell shell = new GroovyShell(binding);
while (!OWLMapping.axiomStack.isEmpty()) {
String s = OWLMapping.axiomStack.pop();
shell.evaluate(s); //350 ms
}
}
Run Code Online (Sandbox Code Playgroud)
我的程序中唯一的瓶颈就在这里。更多的是我必须处理的数据,更多的是我必须等待的毫秒。你有什么建议吗?
如果需要提高 Groovy 性能,可以使用@CompileStatic注释。
这将使 Groovy 编译器以 Java 的方式使用编译时检查,然后执行静态编译,从而绕过 Groovy 元对象协议。
只需用它注释具体方法即可。但请确保您不在该范围内使用任何动态功能。
举个例子:
import groovy.transform.CompileStatic
@CompileStatic
class Static {
}
class Dynamic {
}
println Static.declaredMethods.length
Static.declaredMethods.collect { it.name }.each { println it }
println('-' * 100)
println Dynamic.declaredMethods.length
Dynamic.declaredMethods.collect{ it.name }.each { println it }
Run Code Online (Sandbox Code Playgroud)
不会生成一些额外的方法:
6
invokeMethod
getMetaClass
setMetaClass
$getStaticMetaClass
setProperty
getProperty
8
invokeMethod
getMetaClass
setMetaClass
$getStaticMetaClass
$getCallSiteArray
$createCallSiteArray
setProperty
getProperty