Reputation: 2097
There are many libraries for runtime bytecode generation such as ASM, Javassist, CGLib, and BCEL to name a few. All of these tools are capable of manipulating java bytecode dynamically, and are different from tools like the javac compiler.
I understand that there are some good reasons to generate bytecode and load them into a ClassLoader at runtime. My question is whether or not there are any performance issues or concerns with these tools when generating bytecode for java methods or classes which could be very large.
One scenario might be an application which keeps running for a long time and the generated bytecode would be trivial but continuous (it would keep generating bytecode and/or classes and load/unload them into a classloader continuously).
There is a similar question here, but none of the answers explain any questions about performance. May I have some links to academic articles regarding this issue?
Upvotes: 1
Views: 570
Reputation: 298153
Generating a class at runtime is nothing fancier than filling a byte array with contents. At the point, where the JVM is told to interpret this contents as a Java class, it doesn’t differ from the way a precompiled class loaded from the hard drive is added to the runtime environment.
Since filling a byte array is trivial, the performance depends on the rules which determine the contents. Parsing source code and validating its correctness is an expensive task. On the other hand, generating code according to hardcoded rules, like, e.g. fulfill an interface by calling a single specified method (like lambda instantiation works), usually works much faster than loading the equivalent code from hard drive. Having such rules the typical use case for runtime bytecode generation.
But before thinking about performance you should ask yourself why you are thinking about dynamic byte code generation at all. In most real life scenarios the answer to this question already contains the answer to the question whether performance is relevant at all or why it is expected to be improved by generating code.
Upvotes: 0
Reputation: 1861
I think ASM is the strongest choice for two reasons. First, it's up to date with all of the JVM features, and second, its Visitor Pattern API is very efficient. This second point addresses your performance concerns, I think.
Upvotes: 0
Reputation: 31795
In a real world it won't really matter which framework you'll use. Unless you are planning to generate millions of new methods and load them at the run time, which would be a bad idea to begin with.
Upvotes: 1