int get1(void) { return test; }
void get2(int* arg) { *arg = test;}
static int test = 5;
int main()
{
int result = 0;
result = get1();
get2(&result);
}
get1() 与 get2() - 哪个对嵌入式系统性能更好?
最佳答案
get1()
is usually faster on common architectures. (ARM, MIPS, x86 etc.)
原因:
get2()
使用堆栈上额外的 4 字节内存来传递指针本身。这引入了 2 个额外的内存访问,即在调用get2()
之前要堆栈的PUSH arg
和在取消引用之前从函数堆栈中的POP arg
.
<子> 请注意,取决于 calling-conventions实际参数arg
可以使用 CPU 寄存器传递。但即便如此,在调用函数内调用get1()
之前需要备份寄存器并在之后恢复(即插入/弹出堆栈)。get2()
取消对指针的引用并对该内存位置执行写入操作。在带有 write-through cache 的系统上,由于内存访问,它会增加额外的延迟。get1()
可以通过使用一个 CPU 寄存器来保存返回值来避免这种延迟,这在大多数架构中都很常见。
A general rule of thumb is to reduce the number of parameters to be passed.
通常这被解释为使用指向包含一堆单独参数的数组/结构的指针更好;即 1 个参数(指针)优于 N 个参数(单个值)。
然而,在上述情况下,通过 val 传递返回值(即使用 return 而不是通过 ref)允许在不使用任何参数的情况下实现函数;即 0 个参数优于 1 个参数。
关于c - 通过 Return 与传递指针获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18864872/