【发布时间】:2011-10-21 17:47:24
【问题描述】:
我有一个结构数组,我有一些函数将使用这些结构的几个成员。我想避免在每一行中取消引用。我认为会有一些方法可以在某个内存位置声明一个变量......就像:
someStruct &myStruct = arrayOfStructs[i];
myStruct.x = foo+bar*myStruct.y*myStruct.w;
//Instead of myStruct->x = foo+bar*myStruct->y*myStruct->w;
//It would/should even be possible to access the members in a similar way:
int &x = &myStruct.x;
x = x+4*y+2*z;
//This should avoid overhead of dereferencing the pointer, and offsetting to the member
//by just accessing that particular address of memory as though it was where the variable
//had always been.
这段示例代码可能有助于解释:
#define NUM_BIGSTRUCTS 10000
typedef struct {
int a,b,c;
float d,e,f;
} bigStruct;
bigStruct* arrayOfStructs;
void foo() {
for(int i=0; i<NUM_BIGSTRUCTS; i++) {
bigStruct* temp = arrayOfStructs[i];
temp->f = (temp->d+temp->e)*((float)temp->a+temp->e);
//more similar, with conditionals, etc...
//actually I've got nested loops, and a very very large array
//so any gains per inner loop would decrease my number of instructions exponentially
//So, if I could declare a bigStruct and set its address to the location of a bigStruct in the array
//then I could avoid a dereference every time I access a member of that bigStruct
//Leaving just the member access overhead... which could be handled in a similar manner
//if possible, and when appropriate
}
}
int main(int argx, char** argv) {
arrayOfStructs = g_new0(bigStruct,NUM_BIGSTRUCTS); //Allocate and 0 memory for simplicity
foo();
return 0;
}
我从来没有在 SO 上取得过巨大的成功,所以希望我解释了我想要做的事情。我正在使用 C99 顺便说一句,考虑到 c 的低级性质,我相信这是可能的。
[编辑] 看起来我正在寻找来自 C++ 的“参考”,但对于 C。即便如此,它们只允许赋值一次(初始化),这在我的示例中不起作用。我决定依靠编译器来优化对同一段内存的多次访问。
谢谢, 詹姆斯纽曼
【问题讨论】:
-
@cnicular 我认为根本不需要任何开销。我查看了通过优化 GCC 和 Clang 等编译器生成的汇编代码,我从未想过“嘿,这个偏移量计算了两次,我可以在手写汇编中做得更好”。我对其他构造也有过这样的想法,我认为(我知道在实践中不会发生的潜在别名阻止了编译器进行优化)。
-
为什么要取消引用?查看此 SO 帖子:stackoverflow.com/questions/1329096/…
-
这是相对的。所涉及的算法是 O(N^2),集合涉及数十万个对象,几个复杂的方程涉及每个对象的几个成员。最重要的是,这是用于交互式模拟,所以我每秒至少执行 60 次,并增加了绘图和用户输入的额外开销。这是当前的瓶颈,并且将始终存在于此应用程序中。
-
@James Newman 阅读编译器生成的程序集。有一个最小的指令序列来做你想做的事情,你的编译器可能找到了它。使情况复杂化只会让你远离这个最佳状态。
-
@pascal-cuoq 我认为编译器可能会很好地优化这类事情,但我没有检查过。我会尽力做到这一点。
标签: c pointers c99 dereference