java动态表达式、原生调用、反射性能对比

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();
        }
        
    }
}

输出如下:

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

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

可见用表达式的性能是非常低下的,即使是编译后。如果真的什么时候需要用表达式的话,可以采用动态编译java类的方式实现。(它可以通过调用javac实现参考https://www.cnblogs.com/anai/p/4269858.html,也可以调用JavaCompiler,参考https://www.cnblogs.com/jxrichar/p/4883465.html)这样可以同时达到原生调用和灵活性的目标。

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

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

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

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

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

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

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

猜你喜欢

转载自www.cnblogs.com/zhjh256/p/10797125.html
今日推荐