在开始迭代之前检查 Java 集合是否为空有用吗?

kev*_*rpe 7 java iteration collections garbage-collection micro-optimization

在下面的两种样式中,Iterator分配了一个对象。在迭代之前检查集合是否为空有用吗?我不知道这是否符合“过早优化”的条件。希望对 JVM 垃圾收集器有深入了解的人可以提供见解。

另外,我不知道 Java 编译器如何处理 for-each 循环。我假设样式B会自动转换为样式A。但是......也许包括一张空支票。

循环样式 A

Collection<String> collection = ...
Iterator<String> iter = collection.iterator();
while (iter.hasNext()) {
    String value = iter.next();
    // do stuff
    // maybe call iter.remove()
}
Run Code Online (Sandbox Code Playgroud)

循环样式 B

Collection<String> collection = ...
for (String value : collection) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

循环样式 A(修改)

Collection<String> collection = ...
if (!collection.isEmpty()) {
    Iterator<String> iter = collection.iterator();
    while (iter.hasNext()) {
        String value = iter.next();
        // do stuff
        // maybe call iter.remove()
    }
}
Run Code Online (Sandbox Code Playgroud)

循环样式 B(修改)

Collection<String> collection = ...
if (!collection.isEmpty()) {
    for (String value : collection) {
        // do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

Kin*_*ien 1

不,您不必检查是否为空。第一次迭代将为您解决问题。