[英]Are Iterables.filter and Collections2.filter lazy executed?
[英]Guava: Iterables.filter VS Collections2.filter, any big difference?
我想在Guava中知道Iterables.filter(Iterable, Predicate)
和Collections2.filter(Collection, Predicate)
方法之間是否存在任何差異?
它們似乎都維護迭代順序,並提供實時視圖。 Javadoc說調用Collections2.filter().size()
會迭代所有元素。
假設我有一個謂詞來過濾項目列表,因此我想要在視圖中留下的項目數量(或列表,無關緊要)。 我應該用什么? 這似乎更容易使用Collections2.filter
的size()
是由提供的方法Collection
秒。
但在后台,有沒有區別:
ImmutableList.copyOf(
Iterables.filter(lead.getActions(), isRealActionDoneByUserPredicate)
).size();
和:
Collections2.filter(lead.getActions(),isRealActionDoneByUserPredicate).size();
順便說一句,構建一個ImmutableList
比構建一個普通的ArrayList
更快?
番石榴貢獻者在這里。
Collections2.filter(elements, predicate).size()
是優選的,因為它沒有復制 - 兩個filter
方法都返回一個視圖 - 但是
Iterables.size(Iterables.filter(elements, predicate))
本質上是等價的,並且在沒有任何復制的情況下也會找到答案。
至於構造ArrayList
與ImmutableList
的相對速度,它取決於您使用的構造方法:
ImmutableList.copyOf(collection)
應該花費幾乎完全相同的時間。 (它必須檢查空值,但這很便宜。) ImmutableList.builder()....build()
需要更長的小常量因子,因為它必須在Builder
使用ArrayList
,因為我們事先並不知道將添加多少元素。 ImmutableList.of(...)
將具有大約相等的速度。 也就是說,使用ImmutableList
的概念上的好處往往超過了小的性能成本,特別是如果你經常傳遞列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.