AleMal
AleMal

Reputation: 2077

Java Supplier can optimize object instantiation process?

I have to develop a simple code like this:

public class TestSupplier {


public static void main(String[] args) {
    // TODO Auto-generated method stub

    TestSupplier ts1 = new TestSupplier();

    List<String> lman = ts1.getList(new String[]{"Bob","Tom","Jack","Rob"});
    List<String> lwom = ts1.getList(new String[]{"Barbara","Francesca","Jenny","Sim"});
    List<String> ldog = ts1.getList(new String[]{"Ciuffy","Red","Fido"});


}

public List<String> getList (String[] n) {

    List<String> list1 = new ArrayList<String>();

    for (int i = 0; i < n.length ; i++) {
        list1.add(n[i]);
    }

    return list1;
}

}

Every time program call the "getList" method a new list1 object is created in memory. I was try to find a best way for optimize this behavior and i have modify the code in this way :

public class TestSupplier {

Supplier<List<String>> lsup = ArrayList<String>::new;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    TestSupplier ts1 = new TestSupplier();

    List<String> lman = ts1.getList(new String[]{"Bob","Tom","Jack","Rob"});
    List<String> lwom = ts1.getList(new String[]{"Barbara","Francesca","Jenny","Sim"});
    List<String> ldog = ts1.getList(new String[]{"Ciuffy","Red","Fido"});


}

public List<String> getList (String[] n) {

    List<String> list1 = lsup.get();

    for (int i = 0; i < n.length ; i++) {
        list1.add(n[i]);
    }

    return list1;
}

}

I have create a Supplier as instance variable and in the "getList" method i just call his get method for create the object.

Could this the best approach for optimize the code?

Thanks in advance

Upvotes: 0

Views: 102

Answers (1)

JB Nizet
JB Nizet

Reputation: 691655

That doesn't optimize the code at all. You're still creating a new ArrayList every time, except that instead of calling the constructor directly, you call a supplier that calls the constructor. So it's actually marginally slower, and much less straightforward.

I would just use new ArrayList<>(Arrays.asList(n)). That would at least have the advantage of initializing the ArrayList with an initial size that is large enough to contain all the elements in the array, and would thus avoid resize operations for large arrays. Or just Arrays.asList(n) if a fixed-size list that is backed by the original array is acceptable.

Upvotes: 1

Related Questions