I’m reusing the same ArrayList in a for loop, and I use
for loop
results = new ArrayList<Integer>();
experts = new ArrayList<Integer>();
output = new ArrayList<String>();
....
to create new ones.
I guess this is wrong, because I’m allocating new memory. Is this correct ?
If yes, how can I empty them ?
Added: another example
I’m creating new variables each time I call this method. Is this good practice ? I mean to create new precision, relevantFound.. etc ? Or should I declare them in my class, outside the method to not allocate more and more memory ?
public static void computeMAP(ArrayList<Integer> results, ArrayList<Integer> experts) {
//compute MAP
double precision = 0;
int relevantFound = 0;
double sumprecision = 0;
thanks
ArrayList.clear()will empty them for you; note that doing it your way is also ‘okay’, since Java is garbage-collected, so the old allocations will eventually get cleaned up. Still, it’s better to avoid lots of new allocations (and garbage generation), so the better way would be to move those declarations outside the loop and put in calls toclearinside it.For your second example, either way is fine; primitive types are typically going to get allocated only once (on the stack, when you enter the function), declaring them inside a loop doesn’t increase the cost any. It’s only heap allocations (i.e. calls to
new) you need to worry about.In response to comment:
If it doesn’t make sense for those things to be instance members, then don’t make them such. Also, using
newto ‘clean’ them means allocating new objects every time; definitely don’t do that – if your method needs a new copy of something every time it’s invoked, and it isn’t used anywhere except that method, then it has no business being an instance variable.In general, worrying about such micro-optimizations at this point is counter-productive; you only think about it if you really, absolutely have to, and then measure whether there’s a benefit before doing anything.