How to check bytecode length of java method

时光总嘲笑我的痴心妄想 提交于 2019-12-11 03:23:28

问题


At this moment I participate in big legacy project with many huge classes and generated code. I wish to find all methods that have bytecode length bigger than 8000 bytes (because OOTB java will not optimize it).

I found manual way like this: How many bytes of bytecode has a particular method in Java? , however my goal is to scan many files automatically.

I tried to use jboss-javassist, but AFAIK getting bytecode length is available only on class level.


回答1:


Huge methods might indeed never get inlined, however, but I have my doubts regarding the threshold of 8000. This comment suggests a much smaller limit, though it is platform and configuration dependent anyway.

You are right that getting bytecode length needs to process classes on that low level, however, you didn’t specify what actual obstacle you encountered when trying to do that with Javassist. A simple program doing that with Javassist, would be

try(InputStream is=javax.swing.JComponent.class.getResourceAsStream("JComponent.class")) {
    ClassFile​ cf = new ClassFile(new DataInputStream(is));
    for(MethodInfo mi: cf.getMethods()) {
        CodeAttribute ca = mi.getCodeAttribute();
        if(ca == null) continue; // abstract or native
        int bLen = ca.getCode().length;
        if(bLen > 300)
            System.out.println(mi.getName()+" "+mi.getDescriptor()+", "+bLen+" bytes");
    }
}

This has been written and tested with a recent version of Javassist that uses Generics in the API. If you have a different/older version, you have to use

try(InputStream is=javax.swing.JComponent.class.getResourceAsStream("JComponent.class")) {
    ClassFile​ cf = new ClassFile(new DataInputStream(is));
    for(Object miO: cf.getMethods()) {
        MethodInfo mi = (MethodInfo)miO;
        CodeAttribute ca = mi.getCodeAttribute();
        if(ca == null) continue; // abstract or native
        int bLen = ca.getCode().length;
        if(bLen > 300)
            System.out.println(mi.getName()+" "+mi.getDescriptor()+", "+bLen+" bytes");
    }
}


来源:https://stackoverflow.com/questions/48338337/how-to-check-bytecode-length-of-java-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!