Does Function pointer make the program slow?

前端 未结 8 2589
你的背包
你的背包 2020-11-29 21:10

I read about function pointers in C. And everyone said that will make my program run slow. Is it true?

I made a program to check it. And I got the same results on bo

8条回答
  •  庸人自扰
    2020-11-29 21:34

    A lot of people have put in some good answers, but I still think there's a point being missed. Function pointers do add an extra dereference which makes them several cycles slower, that number can increase based on poor branch prediction (which incidentally has almost nothing to do with the function pointer itself). Additionally functions called via a pointer cannot be inlined. But what people are missing is that most people use function pointers as an optimization.

    The most common place you will find function pointers in c/c++ APIs is as callback functions. The reason so many APIs do this is because writing a system that invokes a function pointer whenever events occur is much more efficient than other methods like message passing. Personally I've also used function pointers as part of a more-complex input processing system, where each key on the keyboard has a function pointer mapped to it via a jump table. This allowed me to remove any branching or logic from the input system and merely handle the key press coming in.

提交回复
热议问题