c - 函数指针与宏与内联

标签 c pointers emulation

我有一个函数可以执行一些检查并从字节数组中读取:

uint8 ReadMem(uint16 addr) {
    if (addr >= 0x8000) return ROM[addr];
    if (addr <  0x2000) return RAM[addr];
    // some more complex checks here
    return OPEN_BUS;
}

由于它由仿真器核心使用,因此每秒被调用数百万次。我想知道与 3 个选项相比,它的总体开销是多少:内联、宏和通过指针调用它。

前两个选项不太好,因为函数不小,而且它被另一个函数调用,大多数操作码都是嵌入的,如果被内联,它会显着增加编译时间和 exe 大小。为了测试函数指针的工作方式,我必须进行重构。有一个选项可以只编译核心一次,与模拟器的其余部分分开,但它也需要重构。

那么到底值得重构吗?指针调用会像宏或内联一样快,还是更快?每种方法的陷阱可能并不那么重要,因为函数非常简单,只是有点长。而且非常频繁。

最佳答案

function pointer vs. macro vs. inline

MACRO -> Compile time resolved
INLINE -> Compile time resolved
Function Pointer -> Runtime resolved
  1. MACRO and INLINE contents replaced at preprocessor stage and that was too fast. but it will not change at runtime that is disadvantage.
  2. Function pointer hold the address of the function. this is useful for passing the function address to another function or calling that function using function pointer.this process takes time more. because of internally it has been done push/pop operation in stack.

关于c - 函数指针与宏与内联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37667573/

相关文章:

尝试通过内存中的地址调用函数时 C++ 程序崩溃(如何修复?)

c++ - 在 C++ 中将元素插入 2D Vector 的顺序

linux - QEMU源码中如何添加新设备?

ios - 我如何在设备上测试我的 NativeScript 应用程序,我是在 Windows 中吗?

c - 使用 fork() 时,getline() 重复读取文件

c - printf 浮点变量和常量有什么区别?

c - 如何在C中生成一个xml文件

c - 使用 kmalloc 分配可执行内存

c++ - 我的类(指向另一个类的指针的容器)似乎无法访问公共(public)构造函数

android - 如何使用 Google Play 服务创建 API-15 模拟器(命令行)