'Local Variable Memory Consumption

Which approach is better to declare local variable in terms of memory consumption?

public List<ResponseObject> mockMethod(RequestObject obj) {
  List<ResponseObject> response = new ArrayList<>();
  if(condition1) {
    response = dataManipulativeMethod1(obj);
    return response;
  } else if(condition2) {
     response = dataManipulativeMethod2(obj);
     return response;
  } else if(condition3) {
     response = dataManipulativeMethod3(obj);
     return response;
  }
}

OR

public List<ResponseObject> mockMethod(RequestObject obj) {
  if(condition1) {
    List<ResponseObject> response = dataManipulativeMethod1();
    return response;
  } else if(condition2) {
     List<ResponseObject> response = dataManipulativeMethod2();
     return response;
  } else if(condition3) {
     List<ResponseObject> response = dataManipulativeMethod3();
     return response;
  }
}

Since only one IF block is going to run per call to mockMethod. I am confused how java manages memory of response list in above two scenarios?

Also which approach is better in case tons of request hit to mockMethod at an instant?



Solution 1:[1]

There is no real difference.

In both examples, the Java Virtual Machine will allocate the memory of response on the stack. When the method returns and the method frame is popped from the stack, all of the local variables become eligible for garbage collection and will (likely) be freed soon.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Strikegently