问题描述
我在Java程序中有一个for循环,该循环遍历一组映射.
I have a for loop in a java program which iterates through a set of maps.
在循环中,我有大约10种不同的if语句,用于检查每个映射中每个键的名称.
Inside the loop I have around 10 different if-statements which checks the name of each key inside the each map.
示例:
for (<String, Object> map : object.entrySet()) {
if (map.getKey().equals.("something") {
do_something;
continue;
}
if (map.getKey().equals.("something_else") {
do_something_else;
continue;
}
if ...
}
添加像这样的连续语句时,我是否可以获得任何性能?
Do I gain any performance when adding continue-statements like this?
当我在IDE中逐步执行代码而没有这些continue语句时,即使第一个匹配,也会测试每个if语句.
When I step through my code in my IDE and NOT have these continue statements, each if-statement will be tested even if the first one matches.
如果我像这样,并且第一个if匹配,则for循环将跳过接下来的9个if语句,并继续下一个对象.也许编译后的代码会对它有所不同,而添加的continue语句实际上会使循环变慢了?
If I have them like this and the first if matches, the for loop will skip the next 9 if-statements and continue with the next object.Maybe the compiled code will treat it differently and the added continue-statements actually makes the loop slower?
推荐答案
而不是一直使用continue
,只需执行一次getKey()
并使用else if
:
Instead of using continue
all the time, do the getKey()
just once and use else if
:
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if (key.equals("something")) {
// ...
} else if (key.equals("something else")) {
// ...
}
}
或使用switch
语句:
for (Map.Entry<String, Object> entry : map.entrySet()) {
switch (entry.getKey()) {
case "something":
// ...
break;
case "something else":
// ...
break;
}
这篇关于在具有许多if语句的for循环中继续使用时,是否可以获得性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!