Search code examples
javagarbage-collectionjvmbytecode

JVM, bytecode, garbage collector and code interpretation by computer (using function which returning "new Object()" many times)


So I would like to be sure (and also the hidden part is I like to have clean code)

When I'm using variable only one time I can create a method:

 private List<Example> getExampleList() {
    return Example.getInstance().getList();
 }

Question:

  1. If I use this only once, this is equivalent to:

    private List<Example> exampleList = Example.getInstance().getList();

  2. What will the consequences be if I use my method many times instead of making a variable that stores this data? Will java load the value and return it even in cases when there was no reason for the value to change ?

  3. What will be the difference between the declaration and using the method?


Solution

  • It depends on if Example.getInstance().getList() creates a new object or not:

    1. If it creates a new object with different content every time, you shall not store the first result into a variable.
    2. If it creates a new object with the same content every time (equivalent objects), you may store into a variable the first returned object and reuse it from then on instead of calling getList. It will produce less calls, less unuseful objects, and thus will improve throughput.
    3. If it does not create new object but always returns the same reference, it goes the same as in point 2.