Home > database >  Should I stop using local variables in Java?
Should I stop using local variables in Java?

Time:02-01

I have these 2 codes in Java and C , which are supposed to do the same thing.

My intuition was that the size (and also content) of object code would be the same for R1 and R2. It's the case for the C (difference of 4 bytes if compiled without -O1). There is a bigger difference for the Java bytecode (R2 is longer), which is surprising for me.

Maybe I'm not looking at the right things and my question might not be relevant, but is it normal that the Java bytecode is so "close" from the source code, and does it mean that it's always more "efficient"/"optimized" to write everything in one-line instead of using local variables ?

C

int A(int a) { return 0; }
int B(int b) { return 0; }
int C(int c) { return 0; }
int D(int d) { return 0; }

int R1() {
  return  A(B(C(3) D(3)));
}

int R2() {
  int d = D(3);
  int c = C(3);
  int b = B(c   d);
  return A(b);
}

// Then R1() and R2() are called in the main()

Java

class MyClass {
  static int A(int a) { return 0; }
  static int B(int b) { return 0; }
  static int C(int c) { return 0; }
  static int D(int d) { return 0; }
  
  static int R1() {
    return  A(B(C(3) D(3)));
  }
  
  static int R2() {
    int d = D(3);
    int c = C(3);
    int b = B(c   d);
    
    return A(b);
  }

  // Then R1 and R2 are called in the Main()
}

When I compiled both of them (g -O1 version 9.4 and javac version 11.0.17), and disassemble R1 and R2, I get this:

C (g -O1 prog.cpp)

R1:
  1251: f3 0f 1e fa             endbr64 
  1255: 53                      push   %rbx
  1256: bf 03 00 00 00          mov    $0x3,           
  • Related