Does the last element in a loop deserve a separate treatment?

前端 未结 13 2073
暖寄归人
暖寄归人 2020-12-15 18:55

When reviewing, I sometimes encounter this kind of loop:

i = begin
while ( i != end ) {    
   // ... do stuff
   if ( i == end-1 (the one-but-last element)          


        
相关标签:
13条回答
  • 2020-12-15 19:24

    In the last snippet you posted, you are repeating code for // .... do stuff.

    It makes sense of keeping 2 loops when you have completely different set of operations on a different set of indices.

    i = begin
    mid = ( end - begin ) / 2 //(the middle element)
    while ( i != mid ) {    
       // ... do stuff
       increment i
    }
    
    while ( i != end ) {
       // ... do other stuff
       increment i
    }
    

    This not being the case, you would still want to keep one single loop. However fact remains that you still save ( end - begin ) / 2 number of comparisons. So it boils down to whether you want your code to look neat or you want to save some CPU cycles. Call is yours.

    0 讨论(0)
提交回复
热议问题