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

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

    I think you have it entirely nailed. Most people fall into the trap of including conditional branches in loops, when they could do them outside: which is simply faster.

    For example:

    if(items == null)
        return null;
    
    StringBuilder result = new StringBuilder();
    if(items.Length != 0)
    {
        result.Append(items[0]); // Special case outside loop.
        for(int i = 1; i < items.Length; i++) // Note: we start at element one.
        {
            result.Append(";");
            result.Append(items[i]);
        }
    }
    return result.ToString();
    

    And the middle case you described is just plain nasty. Imagine if that code grows and needs to be refactored into different methods.

    Unless you are parsing XML loops should be kept as simple and concise as possible.

提交回复
热议问题