Java code optimization, Heap size constraint (use less memory)

Viewed 69

I am facing of memory exception while running this code and the constraint is heap size. Can anyone suggest if there is a way to optimize this code further?

public class getCustomerList {
  public static List <Customer> retrieve() throws ParseException {
    List<Customer> customers = new ArrayList<Customer>();
    for (int i = 0; i < 100000; i++) {
      Customer customer = new Customer();
      customer.setAge(new Integer(i));
      customer.setBirthDate((new SimpleDateFormat("ddMMyyyy")).parse("01061986"));
      customer.setName("Customer" + new String((new Integer(i)).toString()));
      customers.add(customer);
    } 
    return customers;
  }
}
1 Answers

Few ideas that might help:

  1. Make age primitive, if it already is, provide the method an int, not Integer.
customer.setAge(i);
  1. Move SimpleDateFormat outside the loop, currently you create 100000 same instances.
customer.setBirthDate(format.parse("01061986"));
  1. Do you really need 100000 same Date instances for every customer? If you don't, you can get away with setting the same date instance in every customer.
customer.setBirthDate(date);
  1. Current name creation is very inefficient, you create Integer object, then create string from it(and the integer is thrown away), then create copy of said string(and throw away the initial one). Just do:
customer.setName("Customer" + i);
Related