C++ 性能 : template vs boost. 任何

标签 c++ templates boost boost-any

我想知道在任何可以使用模板的地方使用 boost.any(没有 RTTI)类是否会减慢程序速度。由于 boost any 实际上是模板类的包装器,可以说现代编译器优化会产生相同的效果,对吗?

tpl_vs_any.hpp

#include <iostream>
#include <vector>

using namespace std;

template<class T> class tpl
{
    T content;
public:
    tpl(const T& value) : content(value) {}
    operator T() const
    {
        return content;
    }
};

class any
{
public:

    any() : content(0) {}

    any(const any& other) : content(other.content -> clone()) {}

    template<class T> any(const T& value) : content(new holder<T>(value))
    {
    }

    ~any() 
    {
        delete content;
    }

    class placeholder
    {
    public:
        placeholder() {}
        virtual placeholder* clone() const = 0;
    };

    template<class T> class holder : public placeholder
    {
    public:
        T content;

        holder(const T& value) : content(value) {}
        ~holder() {}

        placeholder* clone() const
        {
            return new holder<T>(content);
        }
    };

    template<class T> operator T () const
    {
        return dynamic_cast<holder<T>*>(content)->content;
    }

    placeholder* content;
};

template<class T> void test()
{
    for (int i = 0; i < 10000; ++i)
    {
        vector<T> a;
        a.push_back(23.23);
        a.push_back(3.14);

        double x = (double)a[0];
    }
}

那么这样说是否正确:

test<any>();

完全一样快:

test<tpl<double>>();

假设您知道,就像编译器在第二个示例中所做的那样,boost::any 在这种情况下仅用作 double? (任何类都没有 RTTI)。

我更想知道支持和反对这个论点的论据。

此外,这些方法在特定情况下是否存在差异?

编辑: 性能测试2:

  • 示例 1:1,966.57 毫秒
  • 示例 2:1,320.37 毫秒

好像还是有比较大的区别。

编辑 2: 由于将主要数据类型 double 与类 any 进行比较是不公平的,因此我进行了新测试:

#include "tpl_vs_any.hpp"

int main()
{
    test<any>();
    return 0;
}

速度:1,794.54 毫秒

#include "tpl_vs_any.hpp"

int main()
{
    test<tpl<double>>();
    return 0;
}

速度:1,715.57 毫秒

多次测试,几乎相同的基准。

最佳答案

So would it be correct to say that:

...

Is exactly as fast as:

...

Assuming that you know, just like the compiler does at the second example, that boost::any is only used as double in this situation?

没有。当前的编译器远不及那种级别的自省(introspection)。 boost::any 会更慢。

当然,您可以直接运行代码并自己找出答案。

关于C++ 性能 : template vs boost. 任何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13888175/

相关文章:

c++ - 显式指定位于模板参数包之后的默认模板参数

c++ - 如何在 XCode 中正确包含 Boost 文件(C++ 第三方库)?

c++ - 将 unique_ptr<std::vector> 与 C 风格数组结合使用

C++重载虚拟+运算符

c++ - 如何在Visual Studio中链接库

c++ - 切换返​​回

c++ - 如何清除 C++ 应用程序中的输入缓冲区?

c++ - 关于消息处理系统的建议

c++ - 从 boost::geometry::index::rtree 中删除点的问题

c++ - 如何在不使用 std::async 的情况下使用 std::future?