【问题标题】:Java Supplier can optimize object instantiation process?Java 供应商可以优化对象实例化过程吗?
【发布时间】:2017-03-17 00:05:41
【问题描述】:

我必须像这样开发一个简单的代码:

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

}

每次程序调用“getList”方法时,都会在内存中创建一个新的 list1 对象。 我试图找到优化这种行为的最佳方法,我已经以这种方式修改了代码:

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

}

我已经创建了一个供应商作为实例变量,并且在“getList”方法中我只是调用他的 get 方法来创建对象。

这是优化代码的最佳方法吗?

提前致谢

【问题讨论】:

  • 为了使代码更优雅,我将varargs 参数添加到getList()。供应商在这里没有任何优势,因为每次调用 getList() 时都会创建一个列表,无论是否使用供应商。

标签: java lambda interface functional-programming


【解决方案1】:

这根本没有优化代码。您仍然每次都在创建一个新的 ArrayList,只是不是直接调用构造函数,而是调用调用构造函数的供应商。所以它实际上稍微慢了一点,而且不那么简单。

我只会使用new ArrayList&lt;&gt;(Arrays.asList(n))。这至少具有初始化 ArrayList 的优势,其初始大小足以包含数组中的所有元素,因此可以避免对大型数组进行调整大小操作。如果可以接受由原始数组支持的固定大小列表,则只需 Arrays.asList(n)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多