What's the difference if I instantiate a class within the method or if I instantiated only once?

2

Instance of a class each time I call the method:

 public String formatar(int valorFormatar){
   DecimalFormat df = new DecimalFormat("###,###,###");
   return df.format(valorFormatar);
 }

Now an example of making a single instance of the class:

public class Formatar{
private int valor1;
DecimalFormat df = new DecimalFormat("###,###,###");

    public String formatar(int valorFormatar){
       return df.format(valorFormatar);
    }
}

I have several values that I want to format of this format but I was in doubt as to the best way to use it since for me the two give similar result I would like to know the difference and what is the correct way for me to use it?     

asked by anonymous 24.04.2017 / 15:08

1 answer

4

If you instantiate the variable locally it will certainly be in the stack , which is always desirable if you do not have a reason to use it outside the method.

If you create a variable in the class it will take up memory space in heap in every instance of that class. This can be good or bad.

The advantage of creating in the class is that you do not have to create multiple instances. In addition to saving on the construction of a new object, you will avoid creating multiple objects in heap , which reduces the pressure on the garbage collector , which is quite desirable. If you have to create a new instance in each method that needs formatting, multiple objects will be allocated, one for each instantiation. This is not usually a good thing.

Well, if you are going to instantiate df with "###,###,###" and it will never change, then you do not have to because this variable is an instance. Make it a static variable and it will not consume space in the instance of that class. You will have only one object at no additional cost.

If the method will not access any instance object, the method can be static as well.

If the class is just this and tends to be called several times I would do so:

public class Formatar {
    static DecimalFormat df = new DecimalFormat("###,###,###");

    public static String formatar(int valorFormatar) {
       return df.format(valorFormatar);
    }
}
    
24.04.2017 / 15:24