0

I went through the following link on oracle official site regarding performance tuning, which states "Assigning null to unused variable ease garbage collector to reclaim the memory"

Do I need to adopt the following code practice?

Student student = new Student(100L, "Brian Lara", "II", "B");
public String getSomeValue() {
    String val = "";
    try {
        // Perform some action to get value using student ref. variable
        // val = some val, using student 
    }
    finally {
        this.student = null;
    }
    return val;
}
  • There are 3 possibilities (or may be more) for the instance variable:
    1. Global static instance variable
    2. Global non static instance variable
    3. Local non static instance variable

Please suggest the correct way for the better coding practice.

Another coder
  • 360
  • 5
  • 18
  • 1
    There is overhead to the `try-catch` block; being *clever* is usually exactly the wrong thing to do for performant code. Step one: [Write dumb code](https://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html) Step two: Actually profile the code to determine slow code paths, optimizing without that is just shooting blind. – Elliott Frisch Mar 14 '19 at 04:13
  • You are mixing up terms. An instance variable is never `static` and never local. The best coding practice is to use the narrowest scope needed, i.e. for an item needed only in one method, use a local variable. Then, you never need to set it to `null`. Besides that, the document you’ve linked is not an “oracle official site regarding performance tuning”, which a short look at its title should tell you. It’s a historic document for the “Sun Java System Application Server 9.1”, issued by Sun more than a decade ago. Oracle just archived it when taking over Sun. – Holger Mar 14 '19 at 08:36
  • Setting local variable to `null` can also improve garbage collection, although the majority of the time if you need it, your method is too long or takes too much time. But Oracle didn't fix enhanced for-loops for nothing: https://bugs.java.com/view_bug.do?bug_id=JDK-8175883 – Erwin Bolwidt Mar 14 '19 at 21:55

0 Answers0