performance - Java - Instance variables or method local variables are stays more time in the memory -


i have silly problem in mind clarify. see below code. ex 1, create instance of mysecondclass , use in each method. not create instance each time, in methods whenever want it.

but in ex 2 create instances of mysecondclass inside each method.

i want know implementation in terms of memory consumption (garbage collection) , performance?

ex 1.

 public class myclass {     private mysecondclass var1 = new mysecondclass ();      public void dosomthing(){       var1 .domultiply();    }      public void doanotherthing(){       var1 .docount();    }   }  

ex 2

  public class myclass {          public void dosomthing(){          mysecondclass mysec = new mysecondclass ();         mysec.domultiply();      }        public void doanotherthing(){          mysecondclass mysec = new mysecondclass ();         mysec.docount();       }    }  

update

ok complete code add caller class.

public class caller {    public static void main(string arg[]){      myclass myclass = new myclass ();  // first instance     myclass.dosomthing();      myclass myclass2 = new myclass ();   // second instance     myclass2.doanotherthing();    }  } 

both has same memory consumption (o(1)) latter gives more work garbage collector since after each method run mysecondclass becomes eligible garbage collection.

the first option makes sense if methods functional , can't mess state of var1 (mysecondclass).

so without more information hard tell 1 choose.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -