Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 inside the each map.

Example:

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?

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 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?

like image 438
komen Avatar asked Dec 05 '22 19:12

komen


1 Answers

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")) {
        // ...
    }
}

Or use a switch statement:

for (Map.Entry<String, Object> entry : map.entrySet()) {
    switch (entry.getKey()) {
        case "something":
            // ...
            break;

        case "something else":
            // ...
            break;
}
like image 104
Jesper Avatar answered Dec 24 '22 09:12

Jesper