GotW #2

Temporary Objects(中间对象)
Difficulty: 5 / 10

尽量避免使用中间变量。 因为使用中间变量会降低程序的性能。

Unnecessary temporaries are frequent culprits that can throw all your hard work - and your program's performance - right out the window.

Problem

You are doing a code review. A programmer has written the following function, which uses unnecessary temporary objects in at least three places.

How many can you identify, and how should the programmer fix them?

下面的程序使用了过多的中间变量, 修改如下的程序:

  string FindAddr( list<Employee> l, string name )
  {
    for( list<Employee>::iterator i = l.begin();
         i != l.end();
         i++ )
    {
      if( *i == name )
      {
        return (*i).addr;
      }
    }
    return "";
  }

Solution

Believe it or not, these few lines have three obvious cases of unnecessary temporaries, two subtler ones, and a red herring.

  string FindAddr( list<Employee> l, string name )
                   ^^^^^^^1^^^^^^^^  ^^^^^2^^^^^

1 & 2. The parameters should be const references. Pass-by-value copies both the list and the string, which can be expensive.

为了避免参数的复制,参数的传递方式应该改为 pass by const reference(传递常数应用)。 

[Rule] Prefer passing const& instead of copied values.


    for( list<Employee>::iterator i = l.begin();
         i != l.end();
         i++ )
         ^3^

3. This one was more subtle. Preincrement is more efficient than postincrement, because for postincrement the object must increment itself and then return a temporary containing its old value. Note that this is true even for builtins like int!

对用一般的内置类型, pre-increment 和 post-increment 基本上是代价是一样的。 但是对于复杂的类型, 例如迭代器, 我们更倾向于使用pre-increment, 因为post-increment 在实现时候内部需要一个中间变量存储其旧值, 影响性能。

[Guideline] Prefer preincrement, avoid postincrement.



      if( *i == name )
             ^4

4. The Employee class isn't shown, but for this to work it must either have a conversion to string or a conversion ctor taking a string. Both cases create a temporary object, invoking either operator= for strings or for Employees. (The only way there wouldn't be a temporary is if there was an operator= taking one of each.) 避免发生默认的转型需要中间变量。 

[Guideline] Watch out for hidden temporaries created by parameter conversions. One good way to avoid this is to make ctors explicit when possible.



    return "";
          ^5

5. This creates a temporary (empty) string object.

尽量保证函数内部只有一个return 语句。

More subtly, it's better to declare a local string object to hold the return value and have a single return statement that returns that string. This lets the compiler use the return value optimisation to omit the local object in some cases, e.g., when the client code writes something like:

        string a = FindAddr( l, "Harold" );

[Rule] Follow the single-entry/single-exit rule. Never write multiple return statements in the same function.


[Note: After more performance testing, I no longer agree with the above advice. It has been revised in Exceptional C++.]

  string FindAddr( list<Employee> l, string name )
  ^^^*^^

*. This was a red herring(转移注意力的话). It may seem like you could avoid a temporary in all return cases simply by declaring the return type to be string& instead of string. Wrong (generally see note below)! If you're lucky, your program will crash as soon as the calling code tries to use the reference, since the (local!) object it refers to no longer exists. If you're unlucky, your code will appear to work and fail intermittently, causing long nights of toiling away in the debugger.

最后, 注意一个规则, 永远不要返回一个指向局部对象的references。 

[Rule] Never, ever, EVER return references to local objects.

(Note: Some posters correctly pointed out that you could make this a reference return without changing the function's semantics by declaring a static object that is returned on failure. This illustrates that you do have to be aware of object lifetimes when returning references.)

There are other optimisation opportunities, such as avoiding the redundant calls to end(). The programmer could/should also have used a const_iterator. Ignoring these for now, a corrected version follows:

修改后的优化后的版本如下:

  string FindAddr( const list<Employee>& l, const string& name )
  {
    string addr;
    for( list<Employee>::const_iterator i = l.begin();
         i != l.end();
         ++i )
    {
      if( (*i).name == name )
      {
        addr = (*i).addr;
        break;
      }
    }
    return addr;
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值