2021年3月19日星期五

Local Variable vs Instance Variable

Let's say I have a dog class and I am going to have 10-20 dogs object in my program.

And let's say I have a method Bark that I am going to use every time the user clicks on a button and makes the dog bark randomly.

This is just a simple (not real) example to demonstrate the problem.

public class Dog {      public void Bark() {          int x = (int) Math.random();          String className = this.getClass().getSimpleName();          if (x == 0) {              System.out.println(className + "Bark Now");          }      }  }  

Should I take out int x and String className from Bark method and change them from Local Variable to Instance Variable like this?

public class Dog {      int x = (int) Math.random();      String className = this.getClass().getSimpleName();      public void Bark() {          if (x == 0) {              System.out.println(className + "Bark Now");          }      }  }  

I want to do this change so my program will be less memory hog and more effective by preventing the creation of x primitive and className Object every time the user clicks on the button and instead there will be only one of each for each dog so even the user clicked 10 times on the bark button and therefore the method called 10 times there will be only 1 string object and 1 primitive int instead 10 of each. Does it should even matter?

Let say I have only 1 class Dog just to keep it simple. When should I keep local variable local and when should I change them to instance variable

Edit: I know we are talking about something small but please put it aside the object does not get deleted by itself when the method bark finished the int x and object string className exists in the memory and it will take time for the garbage collection to clean it no? Therefore if I understand correctly the object does not get deleted Immediately after the method finished no?

Edit2: I understand now that local primitive will be deleted right after the method finished. But what about objects such as String/Person/Dog etc... they would be depended by the garbage collector.

I understand that primitive live in the stack such as method, etc object reference lives in the stack too and the object itself lives in the heap. I also understand that an object has an "age" and a life cycle eden|survivor space, etc and it takes time for the garbage collector to clean it so I was not sure if I should take consideration to define it 1 time as an instance variable so if I have 1 dog and the user clicks in 10 sec 10 time on the bark button it will only create the object String I am using 1 time instead 10 times.

https://stackoverflow.com/questions/66717633/local-variable-vs-instance-variable March 20, 2021 at 10:12AM

没有评论:

发表评论