简体   繁体   中英

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

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;
  }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM