java MVEL2/Spring EL表达式、直接调用、反射性能对比

package net.hs.cw.bomp.utils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.mvel2.MVEL;

/**
 * Id 模型
 * 
 * @author Gavin Hu
 * @create 2015/8/26
 */
public class Id implements Serializable {

    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public static Long get(Id id) {
        return id == null ? null : id.getId();
    }

    public static void main(String[] args) {
        Id id = new Id();
        long beg = System.currentTimeMillis();
        for (long i=0;i<100000;i++) {
            id.setId(i);
        }
        System.out.println(System.currentTimeMillis() - beg);
        
        Map<String, Object> paramMap = new HashMap<>();
        String expression = "id.setId(1L);";
        paramMap.put("id", id);
        beg = System.currentTimeMillis();
        Serializable compiled =MVEL.compileExpression(expression);
        for (long i=0;i<100000;i++) {
            MVEL.eval(expression, paramMap);  // 非编译模式
//            MVEL.executeExpression(compiled,paramMap); // 编译模式
        }
        System.out.println(System.currentTimeMillis() - beg);
        beg = System.currentTimeMillis();
        try {
            Field field = Id.class.getDeclaredField("id");
            for (long i=0;i<100000;i++) {
                field.set(id, i);
            }
            System.out.println(System.currentTimeMillis() - beg);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

输出以下:html

6  --原生调用
498   --MVEL2表达式java

239 -- MVEL2 编译后
18   --反射express

还差一个基于Unsafe直接访问的,后面补上。。。。post

可见用表达式的性能是很是低下的,即便是编译后。若是真的何时须要用表达式的话,能够采用动态编译java类的方式实现。(它能够经过调用javac实现参考https://www.cnblogs.com/anai/p/4269858.html,也能够调用JavaCompiler,参考https://www.cnblogs.com/jxrichar/p/4883465.html)这样能够同时达到原生调用和灵活性的目标。性能

根据一些文章的性能评测,对于表达式语言,性能最好的是groovy、其次是MVEL。this

https://www.cnblogs.com/keithmo/p/5186693.htmlspa

https://www.techug.com/post/dynamic-code-in-java.html.net

https://blog.csdn.net/sunnyyoona/article/details/75244442code

https://www.iteye.com/topic/361794htm

https://blog.csdn.net/fhm727/article/details/6543152

http://simpleframework.net/news/view?newsId=028c6068df804c548668b96db31a912b

相关文章
相关标签/搜索