【发布时间】:2021-07-12 16:31:55
【问题描述】:
我正在为我的一些类编写一个标识函数,以记录其调用次数(长话短说:指标)。
目前,我正在尝试计算使用模板与auto 的性能差异/优势。
下面是我正在做的代码中的一个简短示例:
namespace Metrics {
unsigned long identifications = 0;
//auto version
auto identity(auto i) {
//... other stuffs
identifications++;
return i;
};
//template version
template<class I> I identity(I i) {
//... other stuffs
identifications++;
return i;
};
};
还有更多内容,但这是基础。我知道编译器只会为每个函数创建一个函数,即
identity(5);
identity("5");
//generates the functions
int identity(int i) { ... return i; };
const char* identity(const char* i) { ... return i; };
在运行时,哪个更快? 他们有编译时差吗?
由于这个函数被称为很多,我对运行时性能更感兴趣,但也可能有大量的类型要为其生成函数,所以我'我也对哪个在编译时更快感兴趣。
【问题讨论】: