-1

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;
  }
}
Nick B
  • 47
  • 8

1 Answers1

2

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);
Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • 2
    …and stop using the legacy `Date` class. Using [`LocalDate.of(year, month, day)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDate.html#of(int,int,int)), there is no need to parse a string and no conversions between intended semantics and instant (milliseconds since …) semantics. – Holger Sep 12 '22 at 08:44