简体   繁体   中英

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

I have a silly problem in my mind to clarify. see below code. Ex 1 , I create an instance of MySecondClass and use it in each method. Where I do not create an instance each time, in methods whenever I want it.

But in Ex 2 I create instances of MySecondClass inside each method.

I want to know which implementation is good in terms of memory consumption ( garbage collection ) and good 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 to complete the code I add the 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 the same memory consumption ( O(1) ) but the latter gives more work to the garbage collector since after each method run MySecondClass becomes eligible for garbage collection.

The first option makes sense if your methods are functional and you can't mess up the state of var1 ( MySecondClass ).

So basically without more information it is hard to tell which one to choose.

Generally, they will behave differently, after each method call (in Ex 2) objects will be eligible for GC , that though does not mean that they will get cleared after leaving the method immediately. In fact, memory will be reclaimed when GC actually runs, and this happens when there is pressure for the memory either in the young gen or old gen.

If your object creation is cheap and this object is small enough, then most probably you would not even feel that garbage collection occurred (since it is going to happen in the young generation). Unless you are sure that this is the bottle-neck in your application, then move the object as a instance field.

Personal note

I would go for the in-method approach as this would add thread safety and you never know where your class will be used in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM