When using an object repeatedly, is it better to clear the data by setting it to null, or instantiate a new object?
Object a = new Object();
for(...){
...
a = null;
**OR**
a = new Object();
}
Here is the example I’m referring to:
Customer a = new Customer();
Collection<Customer> data = new ArrayList<Customer>();
while (rs != null && rs.next()) {
a = new Customer();
a.setCustId(rs.getLong("CUST_ID"));
a.setPerNo(period);
a.setName(rs.getString("cust_nm"));
if(a!= null)
data.add(a);
}
I’m wondering whether the
a = new Customer();
is the best way to do this or if it should be done differently to save on memory and for optimum performance, because each loop has new customer information to put in. From my understanding, if you create a new customer you’re creating a new object and pointing a to that new object. So the old object a was pointing to will get picked up by the garbage collector – same in the case of setting it to null. Is this a correct understanding?
I would prefer:
Why make the scope any greater than it needs to be?
Likewise, unless I needed a new object, I wouldn’t create one for the sake of it.
It’s hard to say much more from just the description given though – if you can give a more complete and real-world example, we may be able to make more concrete recommendations.
(Note that there’s no indication that you want to use an object repeatedly, so much as using a variable repeatedly. They’re very different concepts.)
EDIT: Looking at your specific example, I’d write it like this:
Note that this doesn’t create any
Customerobjects which are eligible for garbage collection – whereas your original code creates an instance ofCustomerbefore entering the loop, and then ignores the newly created object, instead creating a new one and reassigninga‘s value.