0

Sometimes we hear about brave people who understand and write assembly language for performance reasons, as opposed to using a compiler with a high-level language. Can the same be done on the JVM? I've reviewed the JVM instruction set, and it resembles assembly language in some respects, though it's much higher level (I'm assuming that the system-specific implementations of the JVM are extremely efficient).

Is it possible to, say, write JVM instructions and put them into a Java-executable binary?

Simon Kuang
  • 3,870
  • 4
  • 27
  • 53
  • (http://i.imgur.com/v9sOkZz.png) Why the downvotes? People ask theoretical questions here. – Simon Kuang May 11 '14 at 06:18
  • See e.g. herre: http://stackoverflow.com/questions/6176667/what-jvm-assemblers-are-there - since assemblers exist, I guess some people use them. – Mat May 11 '14 at 06:25
  • "Is it possible to, say, write JVM instructions and put them into a Java-executable binary?" **Obviously** yes! a Java-executable is just a file, so obviously there is no inherent limitation in writing them. The real question: why would anybody do that? If they need speed that bad simply don't use Java and program in a lower level language or in assembly. If you write in JVM bytecode you are *limited* by the performance of the JVM interpreter, so probably you can gain something respect the normal Java compiled program, but the gain/developer cost ratio wouldn't be good. – Bakuriu May 11 '14 at 06:54
  • @Bakuriu I think that's an answer. – Simon Kuang May 11 '14 at 06:55
  • 1
    Don’t use URL shorteners. You are forcing readers to follow it, just to find out that the target is not even remotely related the the JVM instruction set. – Holger Jun 18 '21 at 10:00

1 Answers1

1

Yes. You can do this via the asm library.

In fact, this is typically how people implement non-Java languages on top of the JVM, and how many Java metaprogramming libraries work.

You may very well want to do this for the same kind of metaprogramming capabilities - e.g., generating classes at runtime, or using the InvokeDynamic instruction to generate your own method dispatch rules.

There isn't a whole lot of performance benefit to be gained from using raw Java bytecode rather than writing the corresponding high-level Java (the JIT is your main performance booster, and it's optimized for the sorts of patterns "vanilla" Java code generates) but it does give you flexibility for things that are difficult, verbose, or impossible to express in Java.

Bryce
  • 2,157
  • 17
  • 16