简体   繁体   English

Functor与模板参数

[英]Functor vs template parameters

Is there any performance advantage to be had when using template parameters with static member functions instead of functor-style predicates?? 使用带有静态成员函数的模板参数而不是函子式谓词时,是否有任何性能优势?

For instance, a functor-style sort interface is typically something like this: 例如,仿函数风格的排序界面通常是这样的:

template <typename _Type, typename _Pred>
void sort (
    RandomAccessIterator first,
    RandomAccessIterator last ,
    _Pred less_than
    )
{
// actual sorting code here, calling less_than()...
}

You could do something more like this, and require that _Pred contained a static member function _Pred::less_than : 你可以做更像这样的事情,并要求_Pred包含一个静态成员函数_Pred::less_than

template <typename _Type, typename _Pred>
void sort (
    RandomAccessIterator first,
    RandomAccessIterator last
    )
{
// actual sorting code here, calling _Pred::less_than()...
}

In theory, the first case might dynamically create a temporary functor object on the heap, whereas I believe that the second case is fully evaluated at compile time. 从理论上讲,第一种情况可能会在堆上动态创建一个临时的仿函数对象,而我认为第二种情况在编译时是完全评估的。 I understand that (say) gcc and/or msvc are good at optimising, but can this be done to the same degree in the first case?? 我知道(比方说)gcc和/或msvc擅长优化,但在第一种情况下可以做到相同程度吗?

Also, I'm not trying to rewrite the STL sort routines or anything like that, just an example for a more general functor question... 此外,我不是要重写STL排序例程或类似的东西,只是一个更一般的仿函数问题的例子......

Normal use of sort won't put anything on the heap, for the simple reason that nobody calls malloc or new . 正常使用sort不会在堆上放任何东西,原因很简单,没有人调用mallocnew If your predicate causes a call to malloc or new , either in its constructor or in the comparison, then you only have yourself to blame... 如果你的谓词导致对mallocnew的调用,无论是在构造函数中还是在比较中,那么你只能责怪自己...

It's plausible that some stack will be used for the parameter of type _Pred (you must not call a template parameter _Pred in your code, because _Pred is a reserved symbol. It can be called that in the implementation of std::sort ). 有些堆栈将用于_Pred类型的参数是_Pred (您不能在代码中调用模板参数_Pred ,因为_Pred是一个保留符号。可以在std::sort的实现中调用它)。 But there won't be any associated work to do, beyond what's necessary for any data members that the predicate object might have. 但除了谓词对象可能具有的任何数据成员所必需的之外,不会有任何相关的工作要做。 If the predicate has no data members then the optimizer will have a field day, and if it does have data members then a static member function wouldn't support what the user wants to do. 如果谓词没有数据成员,则优化器将具有字段日,如果它具有数据成员,则静态成员函数将不支持用户想要执行的操作。

As long as operator() in the predicate is non-virtual, the compiler can inline it into the instantiation of sort if it can see the definition and if it feels that's best. 只要谓词中的operator()是非虚拟的,编译器就可以将其内联到sort的实例化中,如果它可以看到定义并且感觉它是最好的。 Of course there are no guarantees what's faster, but there's no reason to suppose that a call to a static member function is any faster or slower than a call to a non-virtual non-static member function, nor that it's any easier or harder to inline. 当然不能保证什么更快,但是没有理由认为对静态成员函数的调用比调用非虚拟非静态成员函数更快或更慢,也没有理由更容易或更难排队。

In theory, the first case might dynamically create a temporary functor object on the heap, whereas I believe that the second case is fully evaluated at compile time. 从理论上讲,第一种情况可能会在堆上动态创建一个临时的仿函数对象,而我认为第二种情况在编译时是完全评估的。

The first case will create a temporary functor object on the stack. 第一种情况是在堆栈上创建一个临时的仿函数对象。 Are you worrying about whether Pred::Pred() will allocate storage? 您是否担心Pred::Pred()是否会分配存储空间? If so, you may as well also worry about whether the static function is going to allocate storage on the heap for some reason. 如果是这样,您也可以担心静态函数是否会出于某种原因在堆上分配存储。

Regardless, most predicate functor objects that work with this sort of idiom have very simple constructors, since their only purpose is to call an overloaded operator () , so the compiler will likely optimize out the object construction and produce a simple function call. 无论如何,使用这种习惯用法的大多数谓词仿函数对象都有非常简单的构造函数,因为它们的唯一目的是调用重载的operator () ,因此编译器可能会优化对象构造并生成一个简单的函数调用。

In the first case, you could create a 在第一种情况下,您可以创建一个

template<class T>
struct CompareByIntProperties {
    CompareByIntProperties(vector<T::*int> props) : props_(props) {}
    bool less_than(const T& a, const T& b) const {
        for (vector<T::*int>::const_iterator it = props_.begin();
             it != props_.end(); ++it) {
            if (a.(**it) < b.(**it)) return true;
            if (a.(**it) > b.(**it)) return false;
        }
        return false;
    }
    vector<T::*int> props_;
};

which would allow you to 这会让你

vector<Foo::*int> properties;
if (compare_foo) properties.push_back(&Foo::foo);
if (compare_bar) properties.push_back(&Foo::bar);
if (compare_qux) properties.push_back(&Foo::qux);
sort(container.begin(), container.end(), CompareByIntProperties<Foo>(properties));

Please forgive any syntax errors, none of this has been compile-checked. 请原谅任何语法错误,这些都没有经过编译检查。 But you get the idea. 但是你明白了。

In the second case, because you're calling a static method, you do not have free reign to customize the comparator like this. 在第二种情况下,因为你正在调用静态方法,所以你没有自由的统治来自定义这样的比较器。

I wouldn't worry about efficiency. 我不担心效率。 If you're not accessing anything non-static, a good C++ compiler will elide the extra object creation/destruction and possibly even inline the comparator. 如果你没有访问任何非静态的东西,一个好的C ++编译器将忽略额外的对象创建/破坏,甚至可能内联比较器。

If _Pred::less_than is not virtual, both solutions are identical, since the compiler knows exactly what function it is and can inline if need be. 如果_Pred::less_than不是虚拟的,则两个解决方案都是相同的,因为编译器确切知道它是什么函数,并且如果需要可以内联。

That is assuming that I'm understanding your code right - real code would be more clear. 假设我正确理解你的代码 - 真正的代码会更清晰。 I assume code 1 does something like if (less_than.compare(a, b)) , and code 2 does if (_Pred::less_than(a, b)) . 我假设代码1执行if (less_than.compare(a, b)) ,而代码2执行if (_Pred::less_than(a, b))

EDIT: I should mention that example 1 would pass the object by value, so you'll incur whatever cost that may involve (like a copy constructor). 编辑:我应该提到示例1将按值传递对象,因此您将承担可能涉及的任何成本(如复制构造函数)。

If I were you, I'd stop worrying about whether or not you'll buy a micro-nano-second by doing it one way vs. the other...and worry more about not using names that are reserved! 如果我是你,我会不再担心你是否会通过一种方式而不是另一种方式购买微纳秒......并且更担心不使用保留的名称!

You've got a long way to go before worrying about crap like this. 在担心像这样的垃圾之前,你还有很长的路要走。 By the time you get there...hopefully you've learned that it's pointless worrying about crap like this. 当你到达那里的时候......希望你已经知道像这样的废话是毫无意义的。

Though, in order to make this an "answer": Neither, your program is ill-formed. 虽然,为了使这个“答案”:你的程序也不是很糟糕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM