C ++ Boost绑定性能 [英] C ++ Boost Bind Performance

查看:130
本文介绍了C ++ Boost绑定性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

绑定函数(使用Boost绑定)时,是否有任何性能影响(正面或负面)?

解决方案

也许,可能不是。



std :: bind 的结果(或者也可以是 boost :: bind )是一个所谓的绑定表达式,它具有由实现确定的un­ know­ able类型。此类型是 Callable ,并且可转换 std :: function code> boost :: function )。



在内部, function 可以)使用类型擦除来处理各种复杂的,有状态的调用和害羞的可能对象。这需要一些动态分配和虚拟分派(虽然不是必要&害羞;莎丽&害羞;所有)的情况。 bind 函数都是有状态的,因为它们存储绑定的参数。



结果是,如果可能的话,你应该避免将绑定表达式转换为函数对象。绑定表达式本身可能更便宜,你不应该害怕使用 bind (例如,当bind­成员函数指针到实例和参数)。只有在真正需要管理可调用实体的异构集合时,才可以自由使用 bind ,但转换为 function p>

以下是两个典型示例:



避免此问题:

  std :: function< int(bool,char)> f = std :: bind(& Foo :: bar,x,12); 

void do_something(std :: function< int()> func,int& acc)
{
acc + = func
}

  auto f = std :: bind(& Foo :: bar,x,12) ; // unknowable type,but completely fine 

template< typename F>
void do_something(F&& func,int& acc)//可以推导出不可知的类型
{
acc + = func
}


Are there any performance impacts (positive or negative) when binding functions (using Boost Bind) ?

解决方案

Maybe, may not be. It depends.

The result of std::bind (or also boost::bind) is a so-called "bind expression", which has an un­know­able type determined by the implementation. This type is a Callable, and it is convertible to an in­stance of std::function (or boost::function).

Internally, function (may) use type erasure to handle various complex, stateful "call­able objects". This entails a dynamic allocation and a virtual dispatch in some (though not neces­sari­ly all) cases. Both bind and function are stateful, since they store the bound arguments.

The upshot is that you should avoid converting a bind expression to a function object if possible. The bind expression itself may be cheaper, and you should not be afraid of using bind (for example when bind­ing member function pointers to instances and arguments). Use bind freely, but conversion to function only if you truly need to manage a heterogeneous collection of callable entities.

Here are two typical examples:

Bad; avoid this:

std::function<int(bool, char)> f = std::bind(&Foo::bar, x, 12);

void do_something(std::function<int()> func, int & acc)
{
    acc += func();
}

Better; prefer this:

auto f = std::bind(&Foo::bar, x, 12);   // unknowable type, but perfectly fine

template <typename F>
void do_something(F && func, int & acc)  // can deduce unknowable types
{
    acc += func();
}

这篇关于C ++ Boost绑定性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆