c - 传递指针或 const 结构是否有速度差异

标签 c gcc struct

在 C 中,结构通常通过指针传递,以防止数据被复制到太多。

不过我想知道,这真的很重要吗?编译器不会阻止不必要的复制吗?

例如,如果我将一个变量标记为const,编译器会优化复制吗?

例子

struct my_t {
    int a;
    int b[24];
}

int generate_updated_myt(const my_t c) {
    // do something with c
    return 0;
}

int generate_updated_myt(const my_t * c) {
    // do something with *c
    return 0;
}

一般来说,这两者之间会有任何速度差异吗?

最佳答案

如果我没理解错的话,你问的是编译器能不能优化

int generate_updated_myt(const my_t c);

这样对 generate_updated_myt() 的调用实际上会传递一个指针而不是对象的实际副本(即,它可以以类似于 C++ const&)。

如果对 c 的本地副本的访问被实现为对传入对象的引用而不是实际副本,请考虑以下人为设计的示例:

#include <stdio.h>

struct my_t {
    int a;
    int b[24];
};

int foo(void);
int generate_updated_myt(const struct my_t c)
{
    int a = c.a;

    foo();  // if c is really a 'pointer' to the passed in object,
            //     then this call to `foo()` may change the object
            //     c refers to.

    if (a != c.a) {
        puts("how did my private copy of `c.a` get changed?");
    }

    return a;
}

struct my_t g_instance;

int main(void)
{
    generate_updated_myt( g_instance);
    return 0;
}

int foo(void)
{
    int counter = g_instance.a++;

    return counter;
}

这是不允许您建议的优化的原因之一。

这甚至没有考虑到 const 很容易被丢弃(即使它可能是糟糕的形式)。

关于c - 传递指针或 const 结构是否有速度差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25813447/

相关文章:

struct - 放入结构中时,值的生命周期不够长

c - 将字符串附加到 C 中的字符串数组

c - 使用 char ** 时出现段错误

c++ - 有没有解决使用STL对用户输入数组进行排序的错误的解决方案?

c - 为什么编译器坚持在这里使用被调用者保存的寄存器?

c - 将 xml 值映射到结构体值

c++ - 我如何在 flex 和 bison 中使用 C++?

c - 无法链接到 opengl 库?操作系统/MSVC

c - strstr 与 c 中的正则表达式

c - 关于指针和结构体的代码中的问题