Currently I'm implementing custom software metric tool using the ASM library. The only way to calculate size of a method via this library is to manually increment some size variable on every instruction visit, which looks somewhat wrong to me. Is there another common way to calculate method bytecode size? Or per-instruction size calculation is reasonable enough?
Manually adding instruction sizes won’t work with ASM, as ASM focuses on processing the instructions and conveniently hides the different forms of semantically identical instructions.
For example, ALOAD_0
(one byte), ALOAD 0
(two bytes), and WIDE ALOAD 0
(four bytes) have all the same meaning and are reported to a MethodVisitor
via a visitVarInsn(Opcodes.ALOAD, 0)
call. Then you don’t have to care about the different forms when processing this instruction, but you don’t know which one was present in the original class file.
Since ASM does not provide an API to directly deal with the Code
attribute, it’s not suitable for this specific task. This answer contains an example how to achieve this with Javassist.