Iterator.hasNext和for-each循环之间有什么关系吗?

3

我正在使用JProfiler来分析我的应用程序,由于这是一个庞大的应用程序,所以我非常关注其性能和效率。
由于分析时间太长,因此我将所有的Iterator.hasNext替换为for-each,但是当我在JProfiler的CPU视图中查看时,它显示了在使用for-each时调用了Iterator.hasNext方法。
为什么会这样呢?这两者之间有任何关系吗? 以下是示例代码:

    List<Map<String, Object>> mapList = jdbcTemplate
                        .queryForList(MAP.SELECT_ALL);
                for (Map<String, Object> map : mapList) {
            list.add(fillPreferenceMaster(preferenceMasterMap));
}

当生成字节码时,它们是相同的东西。 - Sean
3个回答

10
是的,增强型for语句在可迭代集合中使用Iterator,请参见JLS第14.14.2节

If the type of Expression is a subtype of Iterable, then let I be the type of the expression Expression.iterator(). The enhanced for statement is equivalent to a basic for 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 enhanced for statement occurs.


2
在Java中,for-each循环使用基础迭代器机制。因此回答你的问题,代码是相同的。
这很可能不是你的代码瓶颈。您应该使用JProfiler识别前10个方法热点,并找出如何优化这些方法调用。

我正在做那件事,但大部分时间都花在jsp方法上,它们的显示方式非常奇怪。 我不知道哪个标签需要太多时间... - NIVESH SENGAR

0

for-each语句使用迭代器来遍历您的集合。编译器将您的for-each替换为while循环。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接