Is performance gained when using continue in a for-loop with many if-statements?

后端 未结 4 1679
小蘑菇
小蘑菇 2021-01-19 11:12

I have a for loop in a java program which iterates through a set of maps.

Inside the loop I have around 10 different if-statements which checks the name of each key

4条回答
  •  情深已故
    2021-01-19 11:22

    Instead of using continue all the time, do the getKey() just once and use else if:

    for (Map.Entry entry : map.entrySet()) {
        String key = entry.getKey();
        if (key.equals("something")) {
            // ...
        } else if (key.equals("something else")) {
            // ...
        }
    }
    

    Or use a switch statement:

    for (Map.Entry entry : map.entrySet()) {
        switch (entry.getKey()) {
            case "something":
                // ...
                break;
    
            case "something else":
                // ...
                break;
    }
    

提交回复
热议问题