SFINAE的表现和if else
The performance of SFINAE and if else
我知道 if else
可以生成 Pipeline stall (bubble),因为分支预测器不能保持 100% 的正确猜测。一句话,很多if elif elif ... else
表现不好
在C++的模板中,我们有SFINAE。使用 SFINAE,我们可以避免 if else
代码。例如,要检查一个 int 是否为奇数,我们可以编写如下代码:
template <int I> void div(char(*)[I % 2 == 0] = 0) {
// this overload is selected when I is even
}
template <int I> void div(char(*)[I % 2 == 1] = 0) {
// this overload is selected when I is odd
}
这样我们就可以避免
if (I % 2 == 0)
{
// do things
}
else
{
// do other things
}
我的问题是,与if else
相比,SFINAE是否具有更好的性能? SFINAE 能避免 Pipeline 泡沫吗?
从运行时性能的角度来看,您执行哪一个实际上并不重要。 I
在编译时是可知的,在这种情况下,任何半体面的编译器都会为两者输出相同的常量情况,或者不是,在这种情况下,SFINAE 方式根本无法编译。
我知道 if else
可以生成 Pipeline stall (bubble),因为分支预测器不能保持 100% 的正确猜测。一句话,很多if elif elif ... else
表现不好
在C++的模板中,我们有SFINAE。使用 SFINAE,我们可以避免 if else
代码。例如,要检查一个 int 是否为奇数,我们可以编写如下代码:
template <int I> void div(char(*)[I % 2 == 0] = 0) {
// this overload is selected when I is even
}
template <int I> void div(char(*)[I % 2 == 1] = 0) {
// this overload is selected when I is odd
}
这样我们就可以避免
if (I % 2 == 0)
{
// do things
}
else
{
// do other things
}
我的问题是,与if else
相比,SFINAE是否具有更好的性能? SFINAE 能避免 Pipeline 泡沫吗?
从运行时性能的角度来看,您执行哪一个实际上并不重要。 I
在编译时是可知的,在这种情况下,任何半体面的编译器都会为两者输出相同的常量情况,或者不是,在这种情况下,SFINAE 方式根本无法编译。