java 反射访问变量速度测试(jdk1.8)

一百万次字段访问时间简单统计:
直接访问的耗时(78毫秒左右)
jdk反射访问耗时(190毫秒左右)
jdk反射访问(除去getDeclaredField)耗时(80毫秒左右)
cglib访问的耗时(75毫秒左右)

public class ReflectionTest {

    static class User{
        private String name;
        public User() {
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

    /**
     * 测试直接访问的耗时(78毫秒左右)
     */
    @Test
    public void testDirectAccess(){
        countTime(user -> user.getName());
    }

    /**
     * 测试jdk反射访问耗时(190毫秒左右)
     */
    @Test
    public void testJdkReflectionAccess(){
        countTime(user -> {
            final Class userClass = user.getClass();
            try {
                final Field name = userClass.getDeclaredField("name");
                name.setAccessible(true);
                return (String) name.get(user);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * 测试jdk反射访问耗时(80毫秒左右)
     */
    @Test
    public void testJdkReflectionAccess2() throws Exception{
        final Field name = User.class.getDeclaredField("name");
        countTime(user -> {
            try {
                name.setAccessible(true);
                return (String) name.get(user);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * 测试cglib访问的耗时(75毫秒左右)
     */
    @Test
    public void testCglibReflectionAccess(){
        final FastClass fastClass = FastClass.create(User.class);
        final FastMethod name = fastClass.getMethod("getName", null);
        countTime(user -> {
            try {
                return (String) name.invoke(user,null);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        });

    }

    private void countTime(Function function) {
        final User user = new User();
        user.setName("test");
        final Instant start = Clock.systemDefaultZone().instant();
        String name = "";
        for(int i=0;i<1000*1000;i++){
            name = function.apply(user) + i;
        }
        final long millis = Duration.between(start, Clock.systemDefaultZone().instant()).toMillis();
        System.err.println(name);
        System.err.println(millis);
    }
}

你可能感兴趣的:(java 反射访问变量速度测试(jdk1.8))