先说结果:
mvel 1000000次 ===>2950毫秒 100000次 ===>627毫秒
Rhino 1000000次 ===>1889毫秒 100000次 ===>494毫秒
测试代码如下:我用了还算是项目中稍微复杂点的表达式
mvel的性能测试
package com.eyu.ahxy.module.expression;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
/**
* 1000000次 ===>2950毫秒 100000次 ===>627毫秒
* @author bean
*/
public class ComplexMvelTest {
public int getA() {
return 10;
}
public int getB() {
return 10;
}
private static final ParserContext context = new ParserContext();
static {
/** 导入 {@link Math} 中的全部静态方法 */
context.addImport(Math.class);
for (Method method : Math.class.getMethods()) {
int mod = method.getModifiers();
if (Modifier.isStatic(mod) && Modifier.isPublic(mod)) {
String name = method.getName();
context.addImport(name, method);
}
}
}
public static final int NUM = 1000000;
public static String exp = "min(floor(test.a*test.getB()),floor(c+d*e))";
public static Map<String, Object> map = new HashMap<>();
static {
map.put("test", new ComplexMvelTest());
map.put("c", 10);
map.put("d", 10);
map.put("e", 2);
}
final Serializable exp2 = MVEL.compileExpression(exp, context);
// @Test
public void notCompileTest() {
for (int i = 0; i < NUM; i++) {
MVEL.eval(exp, map, Double.class);
}
}
@Test
public void compileTest() {
for (int i = 0; i < NUM; i++) {
Object result = MVEL.executeExpression(exp2, map, Double.class);
// System.err.println(result);
}
}
}
Rhino的性能测试
package com.eyu.ahxy.module.expression;
import org.junit.Test;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
/**
* 1000000次 ===>1889毫秒 100000次 ===>494毫秒
* @author bean
*/
public class RhinoComplexCompileTest2 {
public static final int NUM = 1000000;
public int getA() {
return 10;
}
public int getB() {
return 10;
}
public static String exp = "min(floor(test.a*test.getB()),floor(c+d*e))";
static Context cx = Context.enter();
Script exp2 =cx.compileString(exp, "tt", 1, null);
static Scriptable scope = cx.initStandardObjects();
{
ScriptableObject.putProperty(scope, "c", 10);
ScriptableObject.putProperty(scope, "d", 10);
ScriptableObject.putProperty(scope, "e", 2);
ScriptableObject.putProperty(scope, "test", this);
cx.evaluateString(scope, "function min(a,b){return java.lang.Math.min(a,b)}", null, 1, null);
cx.evaluateString(scope, "function floor(a){return java.lang.Math.floor(a)}", null, 1, null);
}
@Test
public void name() {
for (int i = 0; i < NUM; i++) {
Object result=exp2.exec(cx, scope);
// System.err.println(cx.toString(result));
}
}
}