If you instantiate locally the variable will surely be in stack, which is always desirable if you have no reason to use outside the method.
If you create a variable in the class it will take up memory space in the heap in every instance of this class. This can be good or bad.
The advantage of creating in the class is that you don’t need to create multiple instances. In addition to saving on processing the construction of a new object will avoid creating multiple objects in the heap, which decreases the pressure on Garbage Collector, which is quite desirable. If you have to create a new instance in each method that needs formatting, several objects will be allocated, one for each instance. That’s not usually a good thing.
Make sure you instantiate df
with "###,###,###"
and it’s never going to change, so there’s no reason why this variable is instance. Make it a static variable and then it will not consume space in the instance of this class. You will have one object without additional costs.
If the method will not access any instance object, the method can be static as well.
If class is just that 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);
}
}
I put in the Github for future reference.
In practice nothing. The main difference is that if you use the first way in 50 places and then have to change the format, you will need to change in 50 places. Of course there is the question of this object living in the scope of the class rather than the scope of the method in the second form, but I’m only talking about the superficial part.
– Jéf Bueno
When you use the
new
within the methodformatar
you create a new stack in memory each time you run the method, so it is up to Garbage Collector to remove this new instance from memory when it is no longer in use. When you use the instance within the class you use the same stack every time you run the methodformatar
, thus saving memory usage. Using best practices and optimization is more recommended to use the instance in the same stack, that is within the class.– brow-joe