Should try…catch go inside or outside a loop?

后端 未结 21 1932
眼角桃花
眼角桃花 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 18:06

    If it's inside, then you'll gain the overhead of the try/catch structure N times, as opposed to just the once on the outside.


    Every time a Try/Catch structure is called it adds overhead to the execution of the method. Just the little bit of memory & processor ticks needed to deal with the structure. If you're running a loop 100 times, and for hypothetical sake, let's say the cost is 1 tick per try/catch call, then having the Try/Catch inside the loop costs you 100 ticks, as opposed to only 1 tick if it's outside of the loop.

提交回复
热议问题