If statements inside or outside loops?

前端 未结 6 887
醉梦人生
醉梦人生 2021-02-07 17:32

Is it better if I do this:

foreach my $item ( @array ) {
   if ( $bool ) {
     .. code ..
   }
   else {
     .. code ..
   }
}

or

<         


        
6条回答
  •  后悔当初
    2021-02-07 18:14

    The second will be faster since many fewer comparisons. -- The compare is outside the loop rather than inside.

    And since the comparison variable is a loop invariant, I'd be surprised if it wasn't also clearer coding.

    Actual speed difference (wall clock time) depends on size of the array

提交回复
热议问题