2

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 Answers1

7

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");
    }
}
Holger
  • 285,553
  • 42
  • 434
  • 765
  • oh darn part two of the day! you can find out methods lengths like this? sorry close to zero work with javaassist... damn, I could use this!!! – Eugene Jan 19 '18 at 14:36
  • 1
    @Holder Thank you for examples and explanation ! Honestly I just looked into tutorial: http://jboss-javassist.github.io/javassist/tutorial/tutorial.html and then tried to google other options, but without success. – Wojciech Piotrowiak Jan 19 '18 at 20:18
  • Right, sometimes, things are not covered well by tutorials and you have to browse through the API (in this case [this one](https://jboss-javassist.github.io/javassist/html/?overview-summary.html)) and hope to find inspiration. Anyway, I’m glad I could help. – Holger Jan 22 '18 at 08:08