我想知道在任何可以使用模板的地方使用 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/