Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the number of local variables used in a Java bytecode method not the most economical?

I have a snippet of simple Java code:

public static void main(String[] args) {     String testStr = "test";     String rst = testStr + 1 + "a" + "pig" + 2;     System.out.println(rst); } 

Compile it with the Eclipse Java compiler, and examine the bytecode using AsmTools. It shows:

byte code

There are three local variables in the method. The argument is in slot 0, and slots 1 and 2 are supposedly used by the code. But I think 2 local variables are just enough — index 0 is the argument anyway, and the code needs only one more variable.

In order to see if my idea is correct, I edited the textual bytecode, reduced the number of local variables to 2, and adjusted some related instructions:

edited

I recompiled it with AsmTools and it works fine!

So why don't Javac or the Eclipse compiler do this kind of optimization to use the minimal local variables?

like image 551
pf_miles Avatar asked Jul 28 '19 15:07

pf_miles


People also ask

What is the disadvantage of using bytecode?

Disadvantages of Bytecode:It takes more time to run the bytecode that the machine code which is machine specific. It is difficult to use some platform-specific features because java is platform-independent. Mandatory installation of Java interpreter to run the byte code.

What are the advantages of using bytecode in Java?

Advantages of Bytecode Bytecodes are non-runnable codes that rely on the availability of an interpreter, this is where JVM comes into play. It is a machine-level language code that runs on the JVM. It adds portability to Java which resonates with the saying, “write once, read anywhere”.

How does bytecode work in Java?

Bytecode is essentially the machine level language which runs on the Java Virtual Machine. Whenever a class is loaded, it gets a stream of bytecode per method of the class. Whenever that method is called during the execution of a program, the bytecode for that method gets invoked.

What is bytecode and why is it needed in Java?

Bytecode is the intermediate representation of a Java program, allowing a JVM to translate a program into machine-level assembly instructions. When a Java program is compiled, bytecode is generated in the form of a . class file.


1 Answers

There are several reasons. First off, it's not necessary for performance. The JVM already optimizes things at runtime, so there's no point in adding redundant complexity to the compiler.

However, another major reason noone has mentioned here is debugging. Making the bytecode as close to the original source as possible makes it a lot easier to debug.

like image 122
Antimony Avatar answered Oct 17 '22 11:10

Antimony