If statements inside or outside loops?

前端 未结 6 900
醉梦人生
醉梦人生 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:27

    Everyone seems stuck on the performance issue.

    It's almost always better to never have to repeat code. That is, typing the same thing more than once should be painful to you. Since you haven't said anything about the code in each, I'll assume that you want to do different things in each case. My preference is to separate the details of the iteration from the particular processing.

     my $sub_ref = $bool ? make_true_function() : make_false_function();
    
     foreach my $element ( @array ) {
          $sub_ref->( $element );
          }
    
     sub make_true_function  { sub { ... } }
     sub make_false_function { sub { ... } }
    

    That might lose a tiny bit in performance, but it's a lot easier to look at because it's less tangled code. The foreach doesn't care anything about branching or how you made your decision. This works nicely when you want to have more branches too. As long as the right thing shows up in $sub_ref, you don't change the iteration code.

提交回复
热议问题