Should try…catch go inside or outside a loop?

后端 未结 21 1989
眼角桃花
眼角桃花 2020-11-30 17:33

I have a loop that looks something like this:

for (int i = 0; i < max; i++) {
    String myString = ...;
    float myNum = Float.parseFloat(myString);
            


        
21条回答
  •  余生分开走
    2020-11-30 17:54

    You should prefer the outer version over the inner version. This is just a specific version of the rule, move anything outside the loop that you can move outside the loop. Depending on the IL compiler and JIT compiler your two versions may or may not end up with different performance characteristics.

    On another note you should probably look at float.TryParse or Convert.ToFloat.

提交回复
热议问题