[Java Application Performance and Memory Management] Chapter 5 – Passing objects between methods

Published by

on

Passing by Value

public static void main(String[] args) {
	int localValue = 5; // 1. localValue is pushed into stack and set as int value 5.
	calculate(localValue);
	System.out.println(localValue); // 5. As the localValue variable inside the stack is unchanged, the value is still 5. 
}
public static void calculate(int calcValue) { // 2. Local variable calcValue is newly pushed into the stack. And the value is set as int value 5.
	calcValue = calcValue * 100; // 3. The calcValue will be set as int value 500
} // 4. The calcValue will be popped off from the stack

Passing by Reference – NOT Possible in Java

Passing by Value with Objects

The values of the object can be changed.

Final keyword

  • final keyword makes the assignment to happen only once.
final Customer c;
c = new Customer("John"); // OK
c = new Customer("Susan"); // Compiler Error  
  • Generally, using final keyword is good because it allows the Java compiler to potentially optimize the code.
  • However, final keyword doesn’t stop an object’s values from being changed. Refer to below code example
    • As the setName() changes the object’s value, not the value c which is declared as final, it will run fine.
final Customer c;
c = new Customer("John");
c.setName("Susan"); // OK.

Method Inlining

Basically, inlining is a way to optimize compiled source code at runtime by replacing the invocations of the most often executed methods with its bodies.

https://www.baeldung.com/jvm-method-inlining
  • Essentially, the JIT compiler tries to inline the methods that we often call so that we can avoid the overhead of a method invocation.
  • When we call the inlined method, it doesn’t actually invoke the method, but it returns the value right away.
  • The JIT inlines staticprivate, or final methods in general. And while public methods are also candidates for inlining, not every public method will necessarily be inlined. The JVM needs to determine that there’s only a single implementation of such a method. Any additional subclass would prevent inlining and the performance will inevitably decrease.

Reference

Leave a comment