If语句与函数指针 [英] If-statement vs function pointer

查看:227
本文介绍了If语句与函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是更改事件循环中的行为,具体取决于是否打开或关闭复选框。我能想到的最简单的方法就是每次运行循环时测试复选框状态。

The goal is to change the behaviour in an event loop, depending on whether a checkbox is toggled on or off. The simplest way, that I can think of, is just to test the checkbox state each time the loop is run.

// if-statement

void action() { /* ... */ }


void someLoop() {

  if (checkboxTrue) {
    action();
  }
  // ... other stuff

}

如果使用函数指针,代码会更高效,更清晰,还是更好?像这样:

Would the code be more performant and cleaner or in any other way better, if a function pointer was being used? Like this:

// function pointer

void action() { /* ... */ }
void empty() {}
void (*actionPtr)();


void checkboxChanged(int val) {

  if (val == 1)
    actionPtr = &realAction;
  else
    actionPtr = ∅

}

void someLoop() {

  (*actionPtr)();
  // ... other stuff

}


推荐答案


  1. 一个间接函数调用比一个条件更昂贵。

  1. One indirect function call is more expensive than one if condition.

几个如果条件比间接函数调用更昂贵。

Several if conditions are more expensive than an indirect function call.

在这一点担心速度是没有意义的:

你在等待用户的延迟,你正在处理他可以看到的东西(即不会有大量的复选框)。在这样的详细级别上优化每秒执行不到一百万次的代码绝对没有意义。

Worrying about speed at this point is pointless:
You are waiting on the latency of the user, and you are handling stuff he can look at (i. e. there won't be huge amounts of checkboxes). Optimizing code that is executed less than a million times per second on a detailed level like this is absolutely pointless.

所以,我的建议是:在编程用户界面时,不要担心 if 或函数调用的成本。只考虑你耗时的算法中的这些东西。

So, my advise is: stop worrying about the cost of an if or function call while you are programming a user interface. Only think about such stuff inside your time consuming algorithms.

但是,如果你发现你确实在使用复杂的,如果 / else 梯形图和/或切换语句内部循环,您可以通过替换间接函数调用来优化。

However, if you find that you are indeed using complex if/else ladders and/or switch statements inside your inner loop, you might optimize by replacing those with indirect function calls.

编辑:

你说你每秒有600张支票。假设您只有一个 if 要处理的情况(如果更快的情况),您大致保存不使用函数指针间接,每秒6微秒,即运行时的0.0006%。绝对不值得努力......


You say that you have 600 checks per second. Assuming you have only one if case to handle (the situation where the if is faster), you "save" roughly 6 microseconds per second by not using function pointer indirection, that's 0.0006% of the runtime. Definitely not worth the effort...

这篇关于If语句与函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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