对性能CollectionUtils.isEmpty()或collection.isEmpty()有什么好处

时间:2015-07-29 12:58:37

标签: java performance collections

如果您已经知道该集合不为null,那么对性能有什么好处。 使用Apache Commons lib中的<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/noHistroySign" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_gravity="center" android:gravity="center" android:background="@drawable/sign" /> .... !collection.isEmpty()

或者没有任何性能差异?

5 个答案:

答案 0 :(得分:6)

CollectionUtils.isNotEmpty的代码(假设我们在这里谈论Apache Commons)......

public static boolean isEmpty(Collection coll)
{
    return ((coll == null) || (coll.isEmpty()));
}

public static boolean isNotEmpty(Collection coll)
{
    return (!(isEmpty(coll)));
}

...所以,没有什么区别,一次空检查不会成为你的瓶颈; - )

答案 1 :(得分:4)

其他答案是正确的,但只是为了确定:

你为什么要关心?您的应用程序是否存在性能问题;并仔细分析指出该方法;所以你在寻找替代品?

因为......如果不是......那么它可能就是我们正在关注的 PrematureOptimization

还有另外一个方面:if&#34; java标准库&#34;提供一个功能;我总是喜欢他们来自外部图书馆的东西&#34;。 当然,ApacheCommons现在很公共;但是我只会添加对它的依赖...如果我所有其他代码都已经使用它了。

答案 2 :(得分:1)

差异可以忽略不计(额外的空检查),即使是C1编译器也可以轻松地内联所有调用。一般来说,您不应该担心这些简单方法的性能。即使其中一个慢两倍,它仍然比你的应用程序的其余代码快得多。

答案 3 :(得分:0)

Collection.isEmpty作为在apache libs中定义的CollectionUtils间接使用collection.isEmpty()方法。

虽然两者都没有显着差异,但仅仅是

CollectionUtils.isEmptyNullSafe,正如你所说,你知道集合不是空的,所以两者都同样好(几乎)

答案 4 :(得分:0)

使用以下程序,您可以在列表中看到1000 Integer的清晰结果。 注意:时间以毫秒为单位

collection.isEmpty几乎是0毫秒

CollectionsUtils.isNotEmpty需要78毫秒

public static void main(String[] args){
            List<Integer> list = new ArrayList<Integer>();
            for(int i = 0; i<1000; i++)
                list.add(i);

            long startTime = System.currentTimeMillis();
                list.isEmpty();
            long endTime   = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            System.out.println(totalTime);


            long startTime2 = System.currentTimeMillis();
            CollectionUtils.isNotEmpty(list);
            long endTime2   = System.currentTimeMillis();
            long totalTime2 = endTime2 - startTime2;
            System.out.println(totalTime2);
        }
相关问题