我使用 JProfiler
来分析我的应用程序,因为它是一个巨大的应用程序,所以我非常了解它的性能和效率。
花费的时间太长,所以我将所有 Iterator.hasNext
替换为 for-each
但是当我在 JProfilers CPU View 中看到时,它显示给我 Iterator.hasNext
方法在我使用 for-each
的地方调用。
为什么会这样?这两者之间有什么关系吗?
这是示例代码:
List<Map<String, Object>> mapList = jdbcTemplate
.queryForList(MAP.SELECT_ALL);
for (Map<String, Object> map : mapList) {
list.add(fillPreferenceMaster(preferenceMasterMap));
}
最佳答案
是的,增强的 for
语句使用 Iterator
来隐藏可迭代集合,参见 Section 14.14.2 of the JLS :
If the type of Expression is a subtype of
Iterable
, then let I be the type of the expression Expression.iterator()
. The enhancedfor
statement is equivalent to a basicfor
statement of the form:for (I #i = Expression.iterator(); #i.hasNext(); ) { VariableModifiersopt Type Identifier = #i.next(); Statement }
Where
#i
is a compiler-generated identifier that is distinct from any other identifiers (compiler-generated or otherwise) that are in scope (§6.3) at the point where the enhancedfor
statement occurs.
关于java - Iterator.hasNext 和 for-each 循环之间有什么关系吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9356790/