Java switch vs for loop performance -


i doing this:

the first scenario:

for(int i=0; i<50; i++){         // execute other code here          switch(mycustomint){             case 1:             case 2:             case 3:                 // execude method1                 break;             case 4:                  // execute method2                 break;         }     } 

the second scenario:

 for(int i=0; i<50; i++){         // execute other code here     }    switch(mycustomint){         case 1:         case 2:         case 3:             for(int i=0; i<50; i++){                 // execute method1             }             break;         case 4:             for(int i=0; i<50; i++){                 // execute method2             }             break;     } 

the question:

the first scenario runs loop once, check switch statement 50 times.

the second scenario runs loop twice, check switch statement once.

which better way execute? know in today's technology, difference negligible. still curious 1 is, theoretically, better way execute it?

thank you!

note there semantic difference in terms of when method1 , method2 called (say) i == 42 relative "other code" in for loop: in first, method1/method2 called i == 42 iteration before "other code" of i == 43 through i == 49 iterations done. in second, of "othe code" 50 loop iterations done before first call either method1 or method2.

other semantic difference, doesn't matter. what's readable , maintainable. means first one, what's "readable , maintainable" varies person person. elliott's point second 1 repeats loop header additional 2 times well-taken: opens door bug caused changing 1 of 3 , not 1 or both of other two.

performance: it's not going matter. first requires switch (mycustomint) evaluated 49 times more second. in theory, evaluation costs time. in practice, bet you'd have really, hard time measuring difference, particularly if hotspot (the oracle java runtime) decides hotspot , aggressively optimizes it.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -