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

前端 未结 13 2104
暖寄归人
暖寄归人 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:08

    Which one performs better?

    If the number of items is very large then I would always loop once, especially if you are going to perform some operation on every item. The cost of evaluating the conditional is likely to be less than looping twice.

    Oops, of course you are not looping twice... In which case two loops is preferable. However, I maintain that the primary consideration should be performance. There's no need to incur the conditional in the loop (N times) if you can partition the work by a simple manipulation of the loop bounds (once).

提交回复
热议问题