是切割if语句通过使用函数指针会更有效率? [英] Is cutting if statements by using function pointers going to be more efficient?

查看:189
本文介绍了是切割if语句通过使用函数指针会更有效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果 c>语句出现在高重复循环中,那么这个规则可以尝试

So, there's this rule to try to pull if statements out of high repetition loops:

for( int i = 0 ; i < 10000 ; i++ )
{
    if( someModeSettingOn )  doThis( data[i] ) ;
    else  doThat( data[i] ) ;
}

他们说,最好分解它, :

They say, it's better to break it up, to put the if statement outside:

if( someModeSettingOn )
  for( int i = 0 ; i < 10000 ; i++ )
    doThis( data[i] ) ;
else
  for( int i = 0 ; i < 10000 ; i++ )
    doThat( data[i] ) ;      

(如果你说的是不要自己优化! it!)当然优化器可能会为你做这个。但在典型C ++ Bullshit (我不同意他的观点,例如他对虚拟功能的态度)Mike Acton说为什么让编译器猜测你知道的东西

(In case you're saying "Ho! Don't optimize that yourself! The compiler will do it!") Sure the optimizer might do this for you. But in Typical C++ Bullshit (which I don't agree with all his points, eg his attitude towards virtual functions) Mike Acton says "Why make the compiler guess at something you know? Pretty much best point of those stickies, for me.

那么为什么不使用函数指针呢?

So why not use a function pointer instead?

FunctionPointer *fp ;
if( someModeSettingOn )  fp = func1 ;
else fp = func2 ;

for( int i = 0 ; i < 10000 ; i++ )
{
    fp( data[i] ) ;
}

函数指针是否有一些隐藏的开销?调用直接函数是否有效?

Is there some kind of hidden overhead to function pointers? Is it is efficient as calling a straight function?

推荐答案

在这个例子中,不可能说哪种情况会更快,你需要在目标平台/编译器上配置这个代码来估计它。

In this example it's impossible to say which case will be faster. You need to profile this code on target platform/compiler to estimate it.

一般来说,在99%的情况下,这样的代码不需要被优化。这是邪恶的过早优化的例子。
编写人类可读的代码,并仅在需要之后进行优化。

And in general, in 99% case such code need not to be optimized. It's example of evil premature optimization. Write human-readable code and optimize it only if need after profiling.

这篇关于是切割if语句通过使用函数指针会更有效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆