也许这是显而易见的或愚蠢的问题,所以对不起。
假设我有以下两种通过简单条件遍历集合的方法:
1个
Predicate<SomeObject> pred1 = new Predicate<SomeObject> () {... some condition_1 ...};
Predicate<SomeObject> pred2 = new Predicate<SomeObject> () {... some condition_2 ...};
Iterator<SomeObject> newIterator = Iterators.filter(iterator, pred1);
... do something like Sets.newHashSet(newIterator) ...
newIterator = Iterators.filter(iterator, pred2);
... do something like Sets.newHashSet(newIterator) ...
2
while(iterator.hasNext()) {
SomeObject someObject = iterator.next();
if (condition_1) {
...do something like set.add(someObject)...
} else if (condition_2) {
...do something like set.add(someObject)...
}
}
我是对的,#2比#1快吗?
感谢您的回答!
最佳答案
命令式版本将更快,但是很难确定多少。在我的测试中,一旦变热,两个版本都在1.1微秒内返回。命令式版本方法在95%的情况下运行速度超过5.15微米(随机执行1,000,000次运行),而FluentIterable版本在95%的情况下运行速度超过6.6微米。
番石榴速度非常快,特别是如果可以静态定义谓词和函数。
在下面的示例中,注意谓词组合和FluentIterable的用法。
FluentIterable尤其具有吸引力,因为可以用最少的修改就可以将其替换为Java 8流。
public static class SomeObject {
private final String someString;
public SomeObject(final String someString) {
this.someString = someString;
}
public String getSomeString() {
return this.someString;
}
@Override
public String toString() {
return this.someString;
}
}
public static final Predicate<SomeObject> CONTAINS_A_FILTER = new Predicate<GuavaExample.SomeObject>() {
@Override
public boolean apply(final SomeObject someObject) {
return someObject.getSomeString()
.contains("A");
}
};
public static final Predicate<SomeObject> CONTAINS_B_FILTER = new Predicate<GuavaExample.SomeObject>() {
@Override
public boolean apply(final SomeObject someObject) {
return someObject.getSomeString()
.contains("B");
}
};
public static final Predicate<SomeObject> CONTAINS_A_AND_B_FILTER = Predicates.and(CONTAINS_A_FILTER,
CONTAINS_B_FILTER);
public static final Predicate<SomeObject> CONTAINS_A_OR_B_FILTER = Predicates.or(CONTAINS_A_FILTER,
CONTAINS_B_FILTER);
public static void main(final String... args) {
final List<SomeObject> someObjects = ImmutableList.of(new SomeObject("A"), new SomeObject("AB"),
new SomeObject("B"), new SomeObject("C"));
final Set<SomeObject> containsAandB = FluentIterable.from(someObjects)
.filter(CONTAINS_A_AND_B_FILTER)
.toSet();
// prints [AB]
System.out.println(containsAandB);
final Set<SomeObject> containsAOrB = FluentIterable.from(someObjects)
.filter(CONTAINS_A_OR_B_FILTER)
.toSet();
// prints [A, AB, B]
System.out.println(containsAOrB);
}