栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

通过普通/反射不同调用方式的对比记录Java性能分析通用步骤

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过普通/反射不同调用方式的对比记录Java性能分析通用步骤

将Users类的getName方法分别用以下三种方式

    普通方式反射方式反射方式关闭安全检测

调用1000000000次,记录所用时间,分析三种方式的性能。

//分析性能问题
public class Test {
    //普通方式调用
    public static void test1(){
        Users user = new Users();

        long startTime = System.currentTimeMillis();

        for (int i = 0; i<1000000000; i++){
            user.getName();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("普通方式:" + (endTime-startTime) + "ms");
    }

    //反射方式调用
    public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Users user = new Users();
        Class c = user.getClass();

        Method getName = c.getDeclaredMethod("getName", null);

        long startTime = System.currentTimeMillis();

        for (int i = 0; i<1000000000; i++){
            getName.invoke(user, null);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("反射方式:" + (endTime-startTime) + "ms");
    }

    //反射方式调用,关闭安全检测
    public static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Users user = new Users();
        Class c = user.getClass();

        Method getName = c.getDeclaredMethod("getName", null);
        getName.setAccessible(true);

        long startTime = System.currentTimeMillis();

        for (int i = 0; i<1000000000; i++){
            getName.invoke(user, null);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("反射方式,关闭安全检测:" + (endTime-startTime) + "ms");
    }

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        test1();
        test2();
        test3();
    }
}

普通方式:3ms
反射方式:3348ms
反射方式,关闭安全检测:1506ms

结论
普通方式调用方法的性能远高于反射调用。
应用反射方式时,若某方法调用频繁,可关闭安全检测(setAccessible(true)),可提升约一倍的性能。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/750214.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号