在 constexpr 函数中初始化变量时的性能损失
Performance loss when initializing variables in constexpr functions
根据 ,不可能在 constexpr
函数中保留未初始化的变量。有时出于性能原因,我们不想初始化变量。是否有可能以某种方式 "overload" 函数,因此它允许 constexpr
版本和更高性能的非 constexpr
函数?
例如,考虑自定义 class vec
中的以下 add
函数:
auto add(vec that) const {
vec ret;
for (int i = 0; i < n; i++)
ret[i] = (*this)[i] + that[i];
return ret;
}
constexpr auto add(vec that) const {
vec ret = {};
for (int i = 0; i < n; i++)
ret[i] = (*this)[i] + that[i];
return ret;
}
C++ 编译器非常擅长优化,尤其是在 constexpr
函数内部。初始化很可能会被优化并且没有额外的成本,并且在您的情况下甚至无关紧要,因为声明一个向量已经将其初始化为一个空向量。
根据 constexpr
函数中保留未初始化的变量。有时出于性能原因,我们不想初始化变量。是否有可能以某种方式 "overload" 函数,因此它允许 constexpr
版本和更高性能的非 constexpr
函数?
例如,考虑自定义 class vec
中的以下 add
函数:
auto add(vec that) const {
vec ret;
for (int i = 0; i < n; i++)
ret[i] = (*this)[i] + that[i];
return ret;
}
constexpr auto add(vec that) const {
vec ret = {};
for (int i = 0; i < n; i++)
ret[i] = (*this)[i] + that[i];
return ret;
}
C++ 编译器非常擅长优化,尤其是在 constexpr
函数内部。初始化很可能会被优化并且没有额外的成本,并且在您的情况下甚至无关紧要,因为声明一个向量已经将其初始化为一个空向量。